Skip to content
Tech Interview Prep
Technical interview guide

Advanced Graphs

Weighted shortest paths and connectivity beyond plain BFS/DFS: Dijkstra, Union-Find, and minimum spanning trees.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with implementation notes referring to CPython 3.14 containers.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-17

How do you determine if a graph is bipartite using BFS or DFS, and at what threshold does graph coloring become NP-complete?

Answer

Determining whether an undirected graph is bipartite is identical to asking whether it is 2-colorable: can every vertex be assigned one of two colors such that no adjacent vertices share a color? This is solvable in linear time, $O(V + E)$, using BFS or DFS. In contrast, deciding $k$-colorability is NP-complete for any fixed $k \ge 3$ on general graphs.

Bipartite Verification Mechanism

A graph is bipartite if and only if it contains no odd-length cycles. We verify this by 2-coloring each connected component:

  1. Maintain a color array indexed by vertex, initialized to an unvisited state (e.g., -1).
  2. Iterate through all vertices $0$ to $V-1$. If vertex $i$ is unvisited, assign color[i] = 0 and launch a BFS or DFS traversal.
  3. For each visited vertex $u$ with color $c$, examine every neighbor $v$:
    • If $v$ is unvisited, assign color[v] = 1 - c and push $v$ to the queue/stack.
    • If $v$ is already visited and color[v] == color[u], an odd-length cycle exists; terminate immediately and return False.
  4. If all components are colored without conflicts, the graph is bipartite and the 2-coloring is valid.
Python
from collections import deque

def is_bipartite(graph: list[list[int]]) -> bool:
    n = len(graph)
    color = [-1] * n

    for start in range(n):
        if color[start] != -1:
            continue
        color[start] = 0
        queue = deque([start])

        while queue:
            u = queue.popleft()
            for v in graph[u]:
                if color[v] == -1:
                    color[v] = 1 - color[u]
                    queue.append(v)
                elif color[v] == color[u]:
                    # Found an odd cycle (u and v share the same layer parity)
                    return False
    return True

The Complexity Boundary

  • $k = 1$: Trivial. Graph must contain zero edges ($O(V + E)$).
  • $k = 2$: Linear time ($O(V + E)$) via BFS/DFS 2-coloring.
  • $k \ge 3$: NP-complete. 3-coloring is one of Karp's original NP-complete problems (reducible from 3-SAT). Even on planar graphs with maximum vertex degree 4, 3-coloring remains NP-complete.

Common Pitfalls and Failure Modes

  1. Disconnected Components: Forgetting the outer loop over all vertices leaves disconnected components unvisited, returning a false positive when an unvisited component contains an odd cycle.
  2. Recursion Limit with DFS: In deep graphs (e.g., a path graph with $V = 10^5$), standard DFS hits Python's default recursion limit (sys.getrecursionlimit() = 1000), raising RecursionError. BFS or iterative DFS avoids this entirely.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3

Walk through union-find with path compression, including where engineers most often get it wrong.

Answer

Core answer (first 90 seconds). Union-find keeps a forest where each set is a tree and the root is the representative. find(x) walks parent pointers to the root; union(x, y) links one root under the other. Two optimisations matter. Path compression rewrites every node on the find path to point directly at the root. Union by rank (or by size) attaches the shorter tree under the taller one. Together they give amortised O(α(n)) per operation, where α is the inverse Ackermann function: below 5 for any n that fits in memory (α(2^65536) = 4). Either optimisation alone gives O(log n) find; neither, on an adversarial chain of n unions, gives O(n) per find.

Mechanism. Rank is an upper bound on tree height, not the height itself. When two roots have equal rank you increment the surviving root's rank by one; otherwise rank is unchanged. That single rule is what keeps height logarithmic. Path compression does not change the root, only the pointers along the path, which is why it can be applied freely during a find.

Trace. Eight elements, parent[i] = i, rank[i] = 0.

opparent afterrank after
init0 1 2 3 4 5 6 70 0 0 0 0 0 0 0
union(0,1)0 0 2 3 4 5 6 71 0 0 0 0 0 0 0
union(2,3)0 0 2 2 4 5 6 71 0 1 0 0 0 0 0
union(0,2)0 0 0 2 4 5 6 72 0 1 0 0 0 0 0
union(4,5)0 0 0 2 4 4 6 72 0 1 0 1 0 0 0
union(6,7)0 0 0 2 4 4 6 62 0 1 0 1 0 1 0
union(4,6)0 0 0 2 4 4 4 62 0 1 0 2 0 1 0
union(0,4)0 0 0 2 0 4 4 63 0 1 0 2 0 1 0

find(7) walks 7→6→4→0 and rewrites parent[7]=0, parent[6]=0, parent[4]=0. A later find(5) walks 5→4→0 and rewrites parent[5]=0. After those two finds every node points straight at 0.

Code.

Python
def find(parent, x):
    root = x
    while parent[root] != root:
        root = parent[root]
    while parent[x] != root:          # second pass: compress
        parent[x], x = root, parent[x]
    return root

def union(parent, rank, a, b):
    ra, rb = find(parent, a), find(parent, b)
    if ra == rb:
        return False
    if rank[ra] < rank[rb]:
        ra, rb = rb, ra
    parent[rb] = ra
    if rank[ra] == rank[rb]:
        rank[ra] += 1
    return True

Checked against Python 3.12.

Where engineers get it wrong.

  1. Incrementing rank on every union instead of only on ties. Rank then tracks the number of unions, not the height, and the tree degenerates toward a chain.
  2. Comparing rank[a] and rank[b] instead of rank[find(a)] and rank[find(b)]. The rank of a non-root is stale.
  3. Recursive find that drops the assignment: find(parent[x]) instead of parent[x] = find(parent[x]). No compression, and without rank the recursion depth can hit n.
  4. Trying to undo a union. Path compression is destructive. If you need rollback (offline dynamic connectivity, Kruskal with undo), use union by rank or size with no compression and accept O(log n) find.
  5. Treating the bound as per-call. It is amortised: a single find can still walk O(log n) links before compression kicks in.

Trade-offs.

  • Union by size vs rank: size is exact and you get component sizes for free (percolation, "largest component" queries); rank is a small integer bound and slightly cheaper. Both give O(α).
  • Path halving (parent[x] = parent[parent[x]]) instead of full compression: one pass, no second loop, same amortised bound, often faster because it touches fewer cache lines.
  • No compression at all: choose it when you need persistence or rollback, or when the number of finds is small enough that O(log n) is irrelevant.
  • Recursive find: fine with rank (depth O(log n)), dangerous without it.

Failure detection. A chain-union workload, union(0,1), union(1,2), …, exposes a missing rank rule: find(n) walks n links. Instrument find to count iterations; if the max exceeds roughly 2·log2(n) after warm-up, the rank rule is broken.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain minimum spanning trees and how it changes a production decision.

Answer

The decision it changes. When the objective is the total cost of connecting a set of sites (fiber between racks, WAN links between regions, backhaul in a wireless mesh) the MST is the cheapest set of links that keeps everything reachable. That is the production decision: which links you buy. It is not the decision about latency between any two sites, and treating the two as the same problem is the common mistake.

Mechanism. A spanning tree touches every vertex with exactly V−1 edges and no cycles; the MST is the one of minimum total weight. Two properties make greedy work: the cut property (the lightest edge crossing any partition belongs to some MST) and the cycle property (the unique heaviest edge of any cycle is in no MST). These hold because spanning trees form a graphic matroid, so the exchange argument is valid, which is why Kruskal (sort edges, add if no cycle; O(E log E)) and Prim (grow from a seed with a priority queue; O(E log V) with a binary heap) both return an optimum. Borůvka's algorithm, O(E log V), is the one to reach for when you want to parallelize or run it distributed.

Worked example. Three racks, cable runs A–B 100 m, B–C 100 m, A–C 150 m. The MST is A–B + B–C = 200 m of cable. The path from A to C inside that tree is 200 m, while the direct link is 150 m: the tree is minimal in total, and the A→C path is 33% longer than the shortest path. Buy the MST and you have the cheapest cabling; you do not have the lowest-latency path between A and C.

Scale. For n sites with all pairs as candidates, the graph has n(n−1)/2 edges. At n = 10,000 that is 49,995,000 edges; stored as (u32, u32, f64) that is ~800 MB before any algorithm runs, and Kruskal sorts all of it. In practice you prune: build from a k-nearest-neighbour or Delaunay candidate set, or run Prim over a sparse adjacency structure, and accept that you may miss the true optimum.

Failure modes.

  • No redundancy. An MST is a tree; one link failure partitions the network. If you must survive one failure, the MST is the base layer, not the answer: minimum 2-edge-connected spanning subgraph is NP-hard, so the usual move is MST plus the cheapest edge that closes a cycle.
  • Wrong objective. If the SLO is p99 latency between two sites, you want a shortest-path tree (Dijkstra), not an MST. MST handles negative edge weights; Dijkstra does not: a quick sanity check on which problem you are actually solving.
  • Subset of terminals. If only 5 of 40 racks must be connected, an MST over all 40 can cost far more than the optimal Steiner tree (NP-hard; MST on the metric closure of the 5 terminals is a 2-approximation).
  • Ties. Distinct weights give a unique MST; equal weights give many equally optimal trees, so two runs can return different edge sets. Pin the tie-break if a test compares output.
  • Directed links. MST is undirected. One-way links need a minimum spanning arborescence (Chu–Liu/Edmonds).

A second decision it settles. Cutting the k−1 heaviest edges of an MST yields k single-linkage clusters: the cheap way to bucket services by similarity once you have the tree.

Tools. NetworkX: nx.minimum_spanning_tree(G, algorithm='kruskal'|'prim'|'boruvka'). SciPy: scipy.sparse.csgraph.minimum_spanning_tree returns the MST edges as a sparse matrix. Watch the name collision: IEEE 802.1D Spanning Tree Protocol builds a loop-free tree, not a minimum-weight one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How would you reason about kruskal versus Prim in a system you own?

Answer

Core answer (first 90 seconds)

Two questions decide it: is the edge set already materialised, and how dense is the graph?

  • Edges exist as a list, E within a small factor of V → Kruskal. Sort the E edges by weight, run union-find with path compression and union by rank, stop after V−1 unions. O(E log E), dominated by the sort.
  • Neighbours are generated on demand (points in a metric space, a grid, a streamed graph) or the graph is dense → Prim. The array version is O(V²) time and O(V) memory and never builds an edge list.

The crossover is arithmetic. Kruskal does about E log₂E comparisons; Prim's array version does V². At V = 10,000, V² = 10⁸, so Kruskal's sort exceeds 10⁸ comparisons once E passes ~4.5×10⁶: roughly 9% of the 5×10⁷ possible edges. Below that density Kruskal wins; above it the array scan wins.

VariantTimeMemoryNeedsUse when
Kruskal + union-findO(E log E)O(E + V)full edge listE ≲ V²/log V
Prim, binary heapO(E log V)O(E) worst caseneighbour functionsparse, implicit graph
Prim, array scanO(V²)O(V)dist(u,v) on demanddense, implicit graph

A binary-heap Prim pushes each edge once, so the heap reaches O(E) entries on a dense graph: it does not save memory there. The array version is the one that does.

Failure modes

  1. Kruskal on an implicit dense graph. V = 100,000 points, E = V(V−1)/2 ≈ 5×10⁹. At 12 bytes per edge (two int32 endpoints, one float32 weight) that is ~60 GB before the sort starts. You OOM in edge generation, not in the sort. Detect it by watching RSS against V during generation: it grows quadratically. Fix: array Prim, O(V) memory.

  2. Binary-heap Prim on a dense graph. Same O(E) heap, plus O(E log V) time. V = 10,000 dense: ~5×10⁷ pushes × ~13 sift levels ≈ 6.5×10⁸ comparisons against 10⁸ for the array scan. Detect it in a profile: heapq sift operations dominate and heap length tracks E. Fix: array version, drop-in.

  3. Prim on a disconnected graph. It returns a spanning tree of the component containing the start vertex and says nothing about the rest. If your input can be disconnected, you ship a tree covering a fraction of the vertices. Detect it by asserting the returned edge count equals V−1; anything less means the graph is disconnected. Kruskal returns a spanning forest and the shortfall is visible in the union count.

The array version

Python
# Prim, array scan. O(V^2) time, O(V) memory, no edge list.
# Python 3.12.
def mst(points, dist):
    n = len(points)
    INF = float("inf")
    best = [INF] * n
    seen = [False] * n
    best[0] = 0.0
    total = 0.0
    for _ in range(n):
        u = min((i for i in range(n) if not seen[i]),
                key=best.__getitem__, default=-1)
        if u == -1 or best[u] == INF:
            break                      # disconnected
        seen[u] = True
        total += best[u]
        for v in range(n):
            if not seen[v]:
                d = dist(points[u], points[v])
                if d < best[v]:
                    best[v] = d
    return total, sum(seen)            # (weight, vertices reached)

On points 0, 1, 3 on a line with dist = |a−b|: it returns (3.0, 3). Edges 0–1 (weight 1) and 1–2 (weight 2). On a disconnected input the second value is less than n, which is the signal to check the input.

What I'd actually do

Default to Kruskal when the edges are already a list: it is simpler, the union-find is ten lines, and it handles a disconnected input without a special case. Switch to array Prim the moment the edge list would be materialised from a distance function or the density crosses the crossover above. Reach for the binary-heap Prim only when the graph is sparse and implicit, where its O(E) heap is small in absolute terms.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does strongly connected components guarantee, and what does it deliberately leave open?

Answer

Assume a finite directed graph G = (V, E), reachability by directed paths, and every vertex reaching itself by the empty path.

What it guarantees. Three things. First, SCC decomposition partitions V into maximal classes where every vertex in a class reaches every other: an equivalence relation, so the partition is unique and every vertex lands in exactly one component. Second, contracting each component to a single node yields the condensation, which is always a DAG; a cycle among components would have merged them. Third, that DAG gives a partial order on components: if X reaches Y and Y reaches X they would be the same component, so reachability between components is antisymmetric and acyclic, and at least one topological order exists.

What it deliberately leaves open. Everything that is not reachability. Weights are ignored: a weighted graph has exactly the same SCCs as its unweighted skeleton. Distances and path counts are gone: knowing two vertices sit in different components tells you one reaches the other, not how far or by how many routes. Internal structure is discarded: a single 1000-vertex cycle and a complete digraph on the same 1000 vertices are both one SCC, and the condensation cannot tell them apart. And "strongly connected" is binary: there is no measure of near-connectivity, so a graph one edge away from being a single component looks identical to a graph shattered into a thousand.

A -> B -> C -> A        SCC1 = {A, B, C}
C -> D
D -> E -> D             SCC2 = {D, E}

Condensation:  SCC1 -> SCC2   (a DAG)

Guaranteed: A reaches E, because SCC1 precedes SCC2 in every topological order. Left open: the shortest A→E path is 4 edges (A→B→C→D→E), and the decomposition does not give you that. It also does not tell you SCC1 is a 3-cycle with 3 edges rather than a complete digraph on {A, B, C} with 6 edges: both are one SCC.

GuaranteedLeft open
Unique partition into maximal mutually-reachable classesEdge weights, distances, path counts
Condensation is a DAGWhich topological order (many are valid)
Reachability between components is a partial orderDensity, diameter, edge count inside a component
Every vertex in exactly one componentBridges, min cut, edge/vertex connectivity
One component covering V ⟺ every vertex reaches every otherPeriodicity (matters for Markov chains)

Two follow-ups worth having ready. If the question is really "can I get from anywhere to anywhere", SCC answers it; if it is "how fragile is that reachability", you want bridges or 2-edge-connected components, a different decomposition. And the decomposition is canonical: Tarjan and Kosaraju return the same partition, so the algorithm is an implementation detail: Tarjan is one DFS pass using discovery indices and low-link values, Kosaraju is two passes plus the reversed graph, both O(V+E).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe the condensation graph and the evidence you would collect before relying on it.

Answer

Core answer (first 90 seconds).

The condensation of a directed graph G has one vertex per strongly connected component of G, and an edge A→B whenever some edge of G runs from a vertex in A to a vertex in B. Contracting each SCC to one vertex always yields a DAG: if the condensation had a cycle A→B→…→A, every vertex on that cycle would be mutually reachable, so they would be a single SCC, not several. That is the guarantee. Everything else: that the SCC partition is correct, that reachability is preserved, that the condensation is small enough to be useful: is a property of the specific graph and the specific implementation, and that is what the evidence is for.

Mechanism.

Reachability is preserved because any path in G maps to a path in the condensation: walk the original path and emit a condensation edge each time it crosses a component boundary. Conversely, any condensation path lifts to a path in G, because within a component you can always get from the entry vertex to the exit vertex (strong connectivity), and each condensation edge is realised by a real edge. So u reaches v in G iff comp[u] reaches comp[v] in the condensation. The quotient is acyclic for the reason above: a cycle in the quotient would merge its components.

Artefact: condensation + verification.

Python
from collections import defaultdict

def condensation(n, edges):
    g, rg = defaultdict(list), defaultdict(list)
    for u, v in edges:
        g[u].append(v); rg[v].append(u)

    seen, order = [False]*n, []
    for s in range(n):
        if seen[s]: continue
        stack = [(s, 0)]; seen[s] = True
        while stack:
            u, i = stack.pop()
            if i < len(g[u]):
                stack.append((u, i+1))
                v = g[u][i]
                if not seen[v]:
                    seen[v] = True; stack.append((v, 0))
            else:
                order.append(u)

    comp, c = [-1]*n, 0
    for s in reversed(order):
        if comp[s] != -1: continue
        stack = [s]; comp[s] = c
        while stack:
            u = stack.pop()
            for v in rg[u]:
                if comp[v] == -1:
                    comp[v] = c; stack.append(v)
        c += 1

    dag = sorted({(comp[u], comp[v]) for u, v in edges if comp[u] != comp[v]})
    return comp, c, dag

Trace on n=6, edges (0,1),(1,2),(2,0),(2,3),(3,4),(4,3),(4,5):

  • First pass finish order: 5,4,3,2,1,0.
  • Second pass on the reverse graph in decreasing finish order: comp = [0,0,0,1,1,2], c=3.
  • dag = [(0,1),(1,2)].

So {0,1,2} → {3,4} → {5}, a 3-vertex DAG.

Evidence to collect.

  1. Partition is a partition. Every vertex has exactly one component id; the component sizes sum to n.
  2. Components are maximal. For every edge (u,v) with comp[u] != comp[v], there is no edge (v',u') with comp[v']==comp[v] and comp[u']==comp[u]. If there is, the two components should have been merged. This catches a broken SCC routine.
  3. Condensation is acyclic. Run Kahn's algorithm on the condensation; it must consume all c components. If it stalls, the SCC routine missed a cycle.
  4. Reachability preserved. On small graphs, exhaustively compare reachability in G against reachability in the condensation for all pairs. On large graphs, sample random pairs plus targeted pairs: two vertices in the same SCC, two vertices on a long path, a vertex with no outgoing edges. This catches a wrong edge set in the condensation.
  5. Aggregate correctness. If you propagate a value (count, sum, max) over the condensation, compare against a brute-force propagation on the original graph for a small subgraph. The condensation gives the component-level answer; it does not give the intra-component answer.
  6. Scale and robustness. Recursive Tarjan overflows Python's default recursion limit of 1000 on a chain of a few thousand vertices; use the iterative form above or raise the limit. Measure peak memory for the adjacency lists at your real V and E.
  7. Determinism. Component ids depend on traversal order. If downstream code keys on them, canonicalise (e.g., sort by smallest member) or the same graph can produce different ids across runs.

Trade-offs and failure modes.

Condensation costs one extra O(V+E) pass and O(V+E) memory on top of whatever you were going to run. Tarjan and Kosaraju are both O(V+E) time. The alternative, running the algorithm on the original graph with an SCC-aware traversal, avoids the extra pass but forces every downstream step to handle cycles, which is where the bugs live. Condensation loses intra-component structure: you cannot answer "longest simple path inside an SCC" from the condensation, and that problem stays NP-hard. The failure mode to watch for is running an acyclic-graph algorithm on the original graph without condensing: it either loops forever or produces an answer that depends on traversal order, and casual testing hides it because the happy path often has no cycles.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Walk me through computing strongly connected components with Tarjan's algorithm, then contrast it with Kosaraju's, where does each one actually win?

Answer

Both algorithms partition the vertices into maximal sets where every pair is mutually reachable, and both run in O(V + E) time with O(V) auxiliary space. The difference is one DFS pass versus two, and whether you are willing to build the transpose graph. Tarjan emits each component the moment it closes; Kosaraju needs the whole traversal first.

Tarjan keeps four things: disc[v], the index at which DFS first reaches v; low[v], the smallest disc reachable from v's subtree through at most one edge to a vertex still on the stack; a stack of the vertices in the current partial component; and an on-stack flag per vertex. Initialise low[v] = disc[v] at entry. For each edge v -> w:

  • w unvisited: recurse, then low[v] = min(low[v], low[w]).
  • w on the stack: low[v] = min(low[v], disc[w]).
  • w visited and off the stack: ignore it. w's component closed already.

When low[v] == disc[v], v is the root of an SCC: pop the stack down to and including v, and that set is one component.

Python
def tarjan_scc(g):            # g: list of adjacency lists, Python 3.12
    n = len(g)
    disc = [-1] * n
    low = [0] * n
    on_stack = [False] * n
    stack, comps, time = [], [], 0

    def dfs(v):
        nonlocal time
        disc[v] = low[v] = time; time += 1
        stack.append(v); on_stack[v] = True
        for w in g[v]:
            if disc[w] == -1:
                dfs(w)
                low[v] = min(low[v], low[w])
            elif on_stack[w]:
                low[v] = min(low[v], disc[w])   # off-stack w: do nothing
        if low[v] == disc[v]:
            comp = []
            while True:
                w = stack.pop(); on_stack[w] = False
                comp.append(w)
                if w == v: break
            comps.append(comp)

    for v in range(n):
        if disc[v] == -1:
            dfs(v)
    return comps

Trace on 0->1, 1->2, 2->0, 2->3, 3->4, 4->3, starting at 0:

vdisclow at exitevent
4434->3 back edge to on-stack 3, low = disc[3]
333low == disc: pops {3,4}
2202->0 back edge; 2->3 is now off-stack, ignored
110tree edge to 2 propagates low 0
000low == disc: pops {0,1,2}

Components come out in reverse topological order of the condensation, which Tarjan gives for free and Kosaraju needs a separate sort for.

Three ways this goes wrong, in interviews and in code review:

Relaxing low[v] from a vertex that is no longer on the stack. Take two disjoint cycles 0<->1 and 2<->3 plus one edge 2->0. If DFS closes {0,1} first, the edge 2->0 sets low[2] = min(2, disc[0]) = 0, so low[2] != disc[2] forever and {2,3} is never emitted as its own component. The on-stack test is the only thing keeping closed components closed.

Initialising low[v] to 0 instead of disc[v]. Every low stays 0 or lower, the root condition fires only by accident, and the whole graph gets popped as one component. Set low[v] = disc[v] at entry, never to a constant.

Treating a cross-edge between finished components as a merge. 2->0 makes {2,3} reach {0,1}; it does not make them mutually reachable. The condensation is a DAG and this is still an edge between two components. Only a cycle in the condensation would merge them, and there is none by construction.

Kosaraju is two plain DFS runs: first on G, recording finish order (push a vertex when it finishes); then on G^T, taking vertices in decreasing finish order, where each DFS tree is exactly one SCC. The reason is that the first vertex popped lives in a sink component of G, which is a source component of G^T, so the second pass cannot leak sideways into another component. The cost is the transpose: materialised at O(V + E) extra memory, or scanned edge-by-edge to keep O(V) auxiliary: plus two traversals.

Prefer Tarjan when you want one pass, no transpose, O(V) auxiliary memory, or components as they close in a streaming or online traversal. Prefer Kosaraju when the code must be verified by someone who has never seen Tarjan: the correctness argument is two sentences and there is no on-stack invariant to maintain, and when G and G^T both already exist in memory as they do in many pipeline systems. On asymptotics they tie, so any claim about which is faster is about constants and graph shape: measure it, don't assert it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How do you find the single-source shortest path and longest path in a directed acyclic graph in O(V + E) time, and why does this approach allow negative edge weights?

Answer

What a strong candidate says first. Topologically sort the DAG, then walk the vertices in that order and relax each outgoing edge exactly once. Every edge points forward in the order, so by the time you reach u, every path from the source into u has already been relaxed and d[u] is final. One sort plus one edge pass is O(V + E). Negative weights are safe because finality comes from the graph's structure, not from a greedy comparison: nothing is locked in by "this is the smallest provisional distance I can currently see." Longest path is the same pass with max instead of min (or negate every weight and run the shortest-path pass).

Why the order makes it correct. A topological order guarantees that for every edge (u, v), u precedes v. So when the loop reaches u, all incoming edges to u originate at vertices already processed, and d[u] cannot be improved later: no future vertex can reach back to u, because that would be a cycle. Each vertex is finalized once and each edge is examined once. Dijkstra fails here because it commits a vertex on the assumption that no later path can be shorter; a negative edge can violate that. Topological relaxation never makes that assumption.

Worked trace. Source 0, edges 0→1 (5), 0→2 (3), 1→3 (6), 1→2 (2), 2→3 (7), 2→4 (4), 2→5 (6), 3→4 (−1), 3→5 (1), 4→5 (−2). Kahn's sort yields 0,1,2,3,4,5.

Shortest from 0:

urelaxationsd after
0d[1]=5, d[2]=3[0,5,3,∞,∞,∞]
1d[3]=11; 5+2=7 not < 3[0,5,3,11,∞,∞]
2d[3]=10; d[4]=7; d[5]=9[0,5,3,10,7,9]
310−1=9 not < 7; 10+1=11 not < 9unchanged
47−2=5 < 9 → d[5]=5[0,5,3,10,7,5]
5—final

The shortest path to 5 is 0→2→4→5 = 3+4−2 = 5, and it uses the negative edge 4→5. Longest from 0: u=1 sets d[2]=7 (5+2 beats 3); u=2 sets d[3]=14, d[4]=11, d[5]=13; u=3 sets d[4]=13 (14−1) and d[5]=15 (14+1); u=4 gives 13−2=11, not > 15. Final d_max = [0,5,7,14,13,15], longest path 0→1→2→3→5 = 5+2+7+1 = 15.

Python
from collections import deque

def dag_paths(adj, source, n):
    # Kahn topological sort: O(V + E)
    indeg = [0] * n
    for u in adj:
        for v, _ in adj[u]:
            indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    topo = []
    while q:
        u = q.popleft()
        topo.append(u)
        for v, _ in adj.get(u, []):
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    if len(topo) < n:
        raise ValueError("graph has a cycle")

    # Relax in topological order: O(V + E)
    dmin = [float('inf')] * n
    dmax = [float('-inf')] * n
    dmin[source] = dmax[source] = 0.0
    for u in topo:
        for v, w in adj.get(u, []):
            if dmin[u] + w < dmin[v]:
                dmin[v] = dmin[u] + w
            if dmax[u] + w > dmax[v]:
                dmax[v] = dmax[u] + w
    return dmin, dmax

float('inf') + w stays inf for any finite w, so unreachable vertices never leak into a relaxation; the dmin[u] + w < dmin[v] test is false for them automatically.

AlgorithmTimeNegative weightsLongest path
DAG topological relaxationO(V + E)YesO(V + E) on a DAG
Dijkstra + binary heapO((V + E) log V)NoNP-hard in general
Bellman-FordO(V·E)Yes, detects negative cyclesNP-hard in general

Failure modes. (1) A cycle slips in: Kahn's sort returns fewer than V vertices, and the code raises rather than silently dropping reachable nodes. (2) Longest path on a general graph is NP-hard: the linear pass is only valid because acyclicity removes the choice of which path to extend. (3) If you need the actual path, keep a parent[v] updated alongside each successful relaxation; reconstructing from distances alone is impossible when weights are negative.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does all-pairs shortest paths matter, and where is it irrelevant?

Answer

Core answer. All-pairs shortest paths (APSP) is the right tool when you need distances between many or all pairs and the graph is small or dense enough that the full V×V matrix fits in memory and computes inside your budget. It is the wrong tool when you need distances from one source, a handful of pairs, or when the graph is large and sparse: there, per-query Dijkstra/A* or a specialized distance oracle wins. The deciding variables are query pattern (all pairs vs. few), density (E relative to V²), and whether the matrix is a deliverable or just an intermediate.

MethodTimeMemoryUse when
Floyd–WarshallO(V³)O(V²)dense (E ≈ V²), V up to ~1–2k, full matrix needed, negative edges OK (no negative cycles)
Johnson (Bellman–Ford + V×Dijkstra)O(V·E log V)O(V²) outputsparse, negative edges allowed
V×Dijkstra (binary heap)O(V·E log V)O(V²) outputsparse, non-negative weights
V×BFSO(V·(V+E))O(V²) outputunweighted
Single Dijkstra / A* on demandO(E log V) per queryO(V)few queries

Arithmetic that decides it. Floyd–Warshall performs roughly V³/2 relaxations. V=500 → 6.25×10⁷, tens of milliseconds in C. V=2,000 → 4×10⁹, seconds in C, minutes in pure Python. V=10,000 → 5×10¹¹, hours, and the matrix alone is 10⁸ entries × 8 bytes = 800 MB. That is the wall. On a sparse graph with V=10⁶, E=10⁷, V×Dijkstra costs about 10⁶ × 10⁷ × log ≈ 2×10¹⁴, also infeasible, so on road networks and social graphs you do not compute APSP at all: you answer queries with contraction hierarchies, hub labeling, or sampled approximations.

Where it matters.

  • A precomputed distance matrix for repeated queries on a static graph: small routing domains, game maps, similarity search.
  • Betweenness centrality (Brandes' algorithm) needs all-pairs shortest-path counts; on large graphs you sample sources instead of running all of them.
  • Graph diameter and eccentricity, and transitive closure via the boolean-semiring variant.
  • Clustering and shortest-path kernels in ML, where the full matrix is the feature.
  • Small dense graphs, V in the hundreds to low thousands.

Where it is irrelevant.

  • One origin, many destinations → a single Dijkstra or BFS.
  • A few pairs → bidirectional Dijkstra or A*.
  • Unweighted reachability only → BFS or union-find; no distances are needed.
  • Large sparse graphs → per-query oracles, not a V² table.
  • Rapidly changing edge weights → recomputing APSP is too expensive; use incremental or lazy recompute.

Failure modes. A negative cycle drives Floyd–Warshall's diagonal negative: detect it by checking d[i][i] < 0 after the run. The V² matrix blows memory before it blows time on wide graphs. And the common design error is reaching for APSP when a single-source run answers the actual question; the query pattern, not the algorithm's elegance, is what should pick the method.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach choosing between all-pairs approaches to an engineer who has only seen it as a rule of thumb.

Answer

The 90-second answer. Ask three things before choosing: are there negative edge weights, how dense is the graph, and do you need all pairs or just one source. Then: no negative edges and E ≪ V² → run Dijkstra from every vertex. No negative edges and E ≈ V² → Floyd-Warshall. Negative edges → Johnson's (Bellman-Ford reweight, then Dijkstra from every vertex), because plain Dijkstra is simply wrong there.

Why. Floyd-Warshall is Θ(V³) time and Θ(V²) space regardless of E: its inner loop is dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]), three nested loops over a contiguous matrix. Repeated Dijkstra is O(V·(E + V) log V) with a binary heap: V runs, each O((E + V) log V). Set them equal: V³ = V·E·log₂V → E = V²/log₂V. For V = 500, log₂500 ≈ 9, so the crossover is E ≈ 28,000 edges: average degree ~56. Below that, repeated Dijkstra wins; above it, Floyd-Warshall.

VEFloyd-Warshall V³Repeated Dijkstra V(E+V)log₂V
5002,0001.25 × 10⁸500 · 2,500 · 9 ≈ 1.1 × 10⁷
500250,0001.25 × 10⁸500 · 250,500 · 9 ≈ 1.1 × 10⁹

At V = 500, E = 2,000 repeated Dijkstra is ~11× cheaper; at E = 250,000 Floyd-Warshall is ~9× cheaper.

Trace: why negative edges force the third option. Graph: A→B = 1, A→C = 2, C→B = −2. The true shortest A→B is A→C→B = 0. Dijkstra from A: pop A (0), relax B = 1, C = 2. Pop B (1): B is finalized at 1. Pop C (2), relax B = 2 + (−2) = 0, but B is already settled, so the update is discarded. Dijkstra returns 1. Floyd-Warshall's k-loop over C fixes it: dist[A][B] = min(1, dist[A][C] + dist[C][B]) = min(1, 0) = 0. Same graph, correct answer, because FW revisits every pair for every intermediate vertex.

Failure modes and how you catch them.

  • A negative edge slips in. Dijkstra returns a wrong number with no error. Detect at ingest: reject or flag negative weights, or run Bellman-Ford on a sample and diff it against FW on a small subgraph.
  • Memory blow-up. FW allocates V² entries. V = 100,000 → 10¹⁰ entries, ~40 GB at 4 bytes. Compute V²·4 before allocating; if it doesn't fit, you're on repeated Dijkstra or a blocked, out-of-core FW.
  • Constant factors beat the asymptotics. FW's inner loop is a branchless min over contiguous memory; Dijkstra's heap does pointer-chasing and cache misses. The real crossover sits at higher density than E = V²/log₂V predicts, so benchmark on your graph's actual density rather than trusting the formula.

Johnson's, when negative edges are present. One Bellman-Ford pass from a virtual source gives potentials h[v]; reweight w′(u,v) = w(u,v) + h[u] − h[v] ≥ 0; then run Dijkstra from every vertex on w′. Cost O(VE + V·E log V): worth it only when the graph is sparse and negative edges exist. If it's dense and negative, Floyd-Warshall is the simpler correct choice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

What makes an A-star heuristic admissible and consistent, and what happens to the search when either property fails?

Answer

Both properties are statements about how the heuristic compares to the true remaining cost h*(n), and they buy different guarantees.

Admissibility is h(n) <= h*(n) for every node. It guarantees the first goal node popped from the open set is optimal. The argument is short: when goal t is popped, f(t) = g(t) because h(t) = 0, and every node still sitting on an optimal path has f = g + h <= (cost so far) + (true remaining) = C*. So g(t) <= C*, and since g(t) is the cost of an actual path it is >= C*. Equality.

Consistency, the triangle inequality, is h(u) <= c(u,v) + h(v) for every edge (u,v), with h(t) = 0 and non-negative edge costs. It makes f non-decreasing along any path, so a node popped from the heap already carries its final optimal g: each node expands once, exactly like Dijkstra, giving O((V+E) log V) with a binary heap. Consistency implies admissibility (walk the inequality down the optimal path), so the two are not independent knobs.

propertyguaranteewhen it fails
h(n) <= h*(n)first goal pop is optimaloptimal path is cut off early, path is whatever was cheapest to find
h(u) <= c(u,v)+h(v)each node expands once, no reopeningnodes get re-expanded, or get frozen at a bad g if you forbid reopening

The second row is where people get burned. An admissible but inconsistent heuristic needs node reopening to stay optimal. Here is a graph that breaks a closed-set implementation:

edges:  S->w: 2   S->v: 5   w->v: 2   v->t: 2
h:      h(S)=4    h(w)=4    h(v)=0    h(t)=0
h*:     6         4         2         0        (all admissible)
w->v violates consistency:  4 > 2 + 0

A* with a closed set and no reopening (popping lowest f):

popfgwhat happens
S40push w (2,6) and v (5,5)
v55close v at g=5, push t (7,7)
w62w->v would improve v to g=4: dropped, v is closed
t77return 7

Optimal is S->w->v->t = 6. With reopening, w reopens v at g=4 and the answer is 6. The tell that this is your bug: the same instance returns 7 with a closed list and 6 without one.

An inadmissible heuristic is a speed-for-optimality trade, not a defect, as long as the trade is stated. Weighted A*, f = g + wh with w > 1 over an admissible h, returns a path costing at most wC*: with C* = 6 and w = 1.5 you are promised <= 9. Scale the same admissible h by 1.05 and you get a 5% bound. If h overestimates on some instances already, there is no bound at all: you bought expansions with correctness and got nothing measurable back.

h = 0 is admissible and consistent and collapses A* to Dijkstra (f = g). It is the reference case for profiling: any heuristic that expands more nodes than h = 0 on the same instance is worse than useless.

Two practical notes. Tie-break equal f values towards larger g, which means smaller h and fewer expansions on plateaus without touching the guarantee. And keep units honest: a heuristic in metres feeding a cost function in seconds is silently inadmissible or silently wasted.

For testing, consistency is cheap and complete: evaluate the triangle inequality on every edge, O(E). Admissibility is not, because it needs h*. Sample states, run a reverse Dijkstra from the goal under the real cost function to get h*, and assert h(n) <= h*(n) on the sample. Any time you scale h, re-run that check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

When does a problem reduce to maximum flow, and what does the min cut tell you that the flow value alone does not?

Answer

A problem reduces to maximum flow when you are moving one commodity through capacity-limited arcs, conserving flow at every node except a source and a sink, and the objective is one scalar: how much gets through. Single commodity, conservation at the intermediate nodes, linear capacity per arc: those are the tells. If any of them is false you are not in max-flow territory. The reduction is the modelling step; the algorithm afterwards is the cheap part.

The recognisable constructions:

ProblemGraph you buildFlow valueMin cut
Bipartite matchings→L cap 1, allowed pairs L→R cap 1, R→t cap 1size of a maximum matchingnodes/edges whose removal destroys every match
Edge-disjoint s–t pathsevery edge cap 1number of edge-disjoint paths (Menger)smallest edge set separating s from t
Assignment with limited slotss→task cap 1, task→eligible worker cap 1, worker→t cap = slotstasks staffableworkers or eligibility rules that cap throughput
Circulation with demandssuper-source into deficit nodes, surplus nodes into super-sinkwhether a feasible circulation existsarcs blocking feasibility

Vertex capacities come free: split v into v_in→v_out carrying the capacity you want, and the min cut becomes a min vertex cut.

The flow value is one number; the min cut names the arcs. Once the algorithm stops, search the residual graph from s over edges that still have capacity. The reachable set S is one shore of a minimum cut, and every arc crossing from S to V∖S is saturated and carrying its full capacity. Those arcs are the bottleneck; capacity anywhere else is slack.

Worked example, hypothetical figures: s→A 6, s→B 5, A→B 3, A→t 4, B→t 5. Maximum flow is 9: 4 through A→t and 5 through B→t. The min cut is {A→t, B→t} = 4 + 5 = 9; the source-side cut {s} is 11 and is not tight. Raising s→A from 6 to 60 moves nothing: the value stays 9. Raise A→t to 6 and the value becomes 11, at which point the source arcs bind. That is the gap between a number and a diagnosis: flow says "we can move 9", the cut says "these two links, and only these two, are why".

Recovering the cut is a reachability pass (Python 3.13; each residual edge carries cap and its original capacity orig):

Python
def min_cut(residual, s):
    seen, stack = {s}, [s]
    while stack:
        u = stack.pop()
        for e in residual[u]:
            if e.cap > 0 and e.to not in seen:
                seen.add(e.to); stack.append(e.to)
    return [(u, e.to) for u in seen for e in residual[u]
            if e.orig > 0 and e.cap == 0 and e.to not in seen]

On algorithm choice: Edmonds–Karp is BFS augmenting paths at O(VE²); Dinic's level graph plus blocking flow is O(V²E); push–relabel is O(V²E) generically and O(V²√E) with the highest-label variant, and it usually wins on dense graphs or when you want throughput rather than a readable implementation. Capacity structure often beats the bound. On unit-capacity networks Dinic tightens to O(E·min(V^{2/3}, E^{1/2})), which is where Hopcroft–Karp's O(E√V) for bipartite matching comes from; with capacities bounded by U the work tracks U, so a network with capacities in 1..8 is a different problem from one with 10^9-valued capacities.

Integrality is what makes those reductions mean anything: with integer capacities an integral maximum flow exists, so arc flow reads as a count (3 workers assigned, 2 disjoint paths) rather than a fraction. A fractional result out of a solver is a signal about the model, not the algorithm.

When the model is wrong: nodes that generate or absorb flow want circulation with demands or generalised flow; cost per unit alongside capacity wants min-cost flow; several commodities sharing capacities with their own sources and sinks is multi-commodity flow, NP-hard in general and LP territory; a fixed on/off cost per node makes the objective non-linear in the flow and plain max flow answers a question nobody asked. Detection is cheap: write the per-node conservation constraint and the objective, and look for constant terms per decision or a capacity shared between two products.

In practice: name the reduction before the algorithm, verify that the flow value equals the capacity of the cut you compute from S, and act on the cut. It is both the proof and the list of places where added capacity actually does something.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Compare Edmonds-Karp and Dinic's algorithm for maximum flow: state the running time of each and say when you would choose one over the other.

Answer

Edmonds-Karp is O(VE^2); Dinic is O(V^2 E), and O(E sqrt(V)) on unit networks. Both are exact and capacity-independent: an integral max flow, plus a min cut by max-flow/min-cut. Assume a single commodity, integer capacities, and a residual graph stored as 2E paired arcs (each edge paired with its reverse at index i^1 so the back-edge is O(1) to find).

Edmonds-KarpDinic
MechanismFord-Fulkerson with BFS: one shortest augmenting path per iterationBFS builds a level graph; DFS sends a whole blocking flow per phase
Worst caseO(VE^2)O(V^2 E)
Special casenoneO(E sqrt(V)) on unit networks
E ~ V (sparse)O(V^3)O(V^3)
E ~ V^2 (dense)O(V^5)O(V^4)
CodeBFS + parent pointers + residual updatelevel array, current-arc pointers, DFS

Where the bounds come from. Edmonds-Karp always augments along a shortest residual path, so the s-t distance in the residual graph never decreases and each edge becomes critical only O(V) times: O(VE) augmentations, each a full BFS at O(E), gives O(VE^2). Dinic sweeps every shortest augmenting path of the current length in one phase, so the level distance strictly increases between phases, O(V) phases, and a blocking flow costs O(VE) with plain DFS, giving O(V^2 E). The O(E sqrt(V)) figure is for unit networks: every non-terminal vertex has one unit-capacity incoming edge or one unit-capacity outgoing edge, which is exactly bipartite matching as flow, and it matches Hopcroft-Karp. It does not follow for graphs where capacities are merely small.

Choosing. Compare the bounds by their ratio, which is E/V: reading V^2 E against VE^2 by eye is the trap, since V^2 E looks larger while being the better bound whenever E > V. Sparse, E ~ V: the bounds coincide at O(V^3), so Edmonds-Karp's roughly thirty lines of BFS beat Dinic's level graph, current-arc bookkeeping and DFS. Dense, E ~ V^2: Dinic's bound is better by a factor of about V; at V = 2,000 and E = 2x10^6 that is a factor of 1,000, and at that gap constants stop mattering. Dinic also wins when capacities are skewed: Edmonds-Karp pays one BFS per unit of flow in the worst case, while Dinic sends a blocking flow per phase and keeps the phase count small. So: Edmonds-Karp for hundreds to a few thousand vertices, one-shot jobs, code that has to be reviewable in twenty minutes. Dinic is the default at scale and for matching-as-flow. Push-relabel with the gap and relabel heuristics (O(V^3) for relabel-to-front) is the option for very large dense instances where you want the fastest practical throughput and can carry the implementation.

Failure modes: drop the current-arc optimization and dead arcs get rescanned every DFS, so the blocking flow stops being linear per phase. Count edge scans per phase and you will see it; the recursive blocking-flow DFS blows the stack on long level graphs; and treating O(E sqrt(V)) as a claim about any graph with small capacities quietly overstates the guarantee.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does bipartite matching as flow change if the workload grows by two orders of magnitude?

Answer

The reduction doesn't change; the cost model does. Source → left, left → right, right → sink, all capacities 1; an integral max flow is a max matching. What changes at 100× is that the work is not linear in the input, and on dense graphs it is nowhere near linear.

The arithmetic. Hopcroft-Karp is O(E√V). Dinic on a unit-capacity network hits the same O(E√V) bound, so "Hopcroft-Karp beats general flow" only holds against general-capacity flow (push-relabel O(V²E), plain Dinic O(V³)). Against the right baseline, the √V is what bites.

Grow V and E by 100× each:

shapeE afterworkgrowth
sparse, E = cV100E100E · 10√V1000×
dense, E = V²/4100E(100V)^2.5100,000×

Concretely: V=10⁴, E=10⁵ → E√V = 10⁷ ops, ~10 ms. V=10⁶, E=10⁷ → 10¹⁰ ops, tens of seconds. A 100× input is a 1000× runtime; a dense 100× input is 100,000×.

Where it actually breaks, in the order the bottlenecks hit:

  1. Memory before time on dense graphs. The residual graph stores 2 arcs per edge; at ~16 bytes/arc that is 32 bytes/edge. 10⁷ edges ≈ 320 MB, 10⁹ edges ≈ 32 GB. You exhaust RAM before you exhaust patience.
  2. Phases. Hopcroft-Karp runs O(√V) phases; 100× V is 10× more phases, each scanning all E (100× more): that is the 1000×.
  3. Cache. Each phase's BFS/DFS walks adjacency with random access. At 10⁹ edges the working set is far past LLC, so the constant factor degrades on top of the asymptotics.

When to abandon the flow formulation.

  • Dense graph, near-maximum is enough: greedy plus bounded local augmentation (Karp-Sipser) is O(E) and lands within a few percent. Ad allocation and assignment heuristics live here.
  • Graph decomposes into components: run per-component and parallelize. Near-linear speedup, cheapest win available.
  • Edges arrive over time: online matching (ranking / water-filling) with competitive-ratio guarantees, not a batch solver.
  • Exact max matching at 10⁹ edges: specialized solvers (LEMON push-relabel, GPU bipartite matching), not a hand-rolled Dinic.

Failure modes to name. Assuming 100× input means 100× time under-provisions by 10×. Recursive DFS augmenting paths blow the stack at large V: write the search iteratively. And a greedy-only matcher passes every small test while silently returning a maximal-but-not-maximum matching; the gap only surfaces on an adversarial input distribution.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

A teammate proposes a design that hinges on bridges and articulation points. How do you evaluate it?

Answer

Answer

Start by pinning down the claim. "The design hinges on bridges and articulation points" is a claim that the system breaks when exactly one edge, or one vertex, is removed. So the first thing I check is whether single-element disconnection is the property the design actually needs. If the requirement is "survives any one link failure," bridges and APs are the right abstraction and they're cheap to compute. If the requirement is "survives k failures," "stays within a latency or capacity budget," or the graph is directed, the design is answering a different question than the one that matters, and correct bridge-finding won't rescue it.

Assumptions I'd make the teammate state out loud: the graph is undirected; the topology is static or changes rarely; "connected" means reachable, not "has enough capacity"; and the vertices and edges are at the right granularity (a vertex is a host, not a rack, or the answer is wrong at the level that matters).

Cost is not where the risk is. All bridges and APs come out of one DFS in O(V+E). The static pass is not the problem. The problem is the dynamic case: if edges are added or removed at runtime, recomputing from scratch costs O(V+E) per change, and incremental bridge maintenance is substantially more involved than the static pass. There's no trivial drop-in. So I'd ask how often the topology changes and whether the design recomputes or maintains.

Correctness traps that flip the answer. Three I'd check by hand:

  • Parallel edges. Two links between A and B: neither is a bridge. A DFS that tracks only the parent vertex skips both edges back to A and reports a false bridge. Tracking the parent edge fixes it.
  • The DFS root. The root is an articulation point iff it has two or more children in the DFS tree: the low-link comparison alone misses this.
  • Directed graphs. Bridges are defined for undirected graphs. A directed dependency graph needs dominators (or strong bridges), not this algorithm.

Trace for the parallel-edge case, A: B with edges e1 and e2, DFS from A:

disc[A]=low[A]=0. Take e1 to B: disc[B]=low[B]=1. At B, e1 is the parent edge (skip); e2 goes to A, already discovered, so low[B]=min(1, disc[A]=0)=0. Back at A: low[B]=0 > disc[A]=0 is false, so no bridge. Correct. Track only the parent vertex and both edges to A get skipped, low[B] stays 1, and you report a bridge that isn't there.

What the tool can and can't express. Bridges are the λ=1 case of edge connectivity. If the design needs "how many simultaneous failures disconnect this," bridges are too weak: you want min-cut / max-flow.

Design claimRight tool
Disconnects on removal of one edge/vertexBridges / articulation points, O(V+E)
Disconnects on removal of k edgesMin-cut / max-flow
Directed dependency, single point of failureDominators
Capacity or latency, not reachabilityFlow / shortest-path, not connectivity

Failure modes and how I'd detect them. The model can be right and the system still wrong: a bridge in the graph may not be a real single point of failure if traffic reroutes at a layer the graph doesn't model, and a non-bridge can still be a single point of failure if every path shares a link the model treats as independent. Detect by validating the graph against reality: remove the edge in a chaos experiment and see whether the system actually partitions, not by trusting the model.

When not to use it. If the topology churns faster than you can recompute, if you need k-fault tolerance, or if the graph is directed, don't build on bridges. Otherwise it's the right, cheap tool: just make the static, undirected, unit-capacity assumptions visible in the design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of eulerian paths?

Answer

Refuse in two situations: the design's correctness depends on an Eulerian trail existing and the degree or connectivity conditions fail, or the design has modelled a vertex-covering problem as an edge-covering one.

Why the degree condition works. Every time a trail passes through a vertex it consumes one edge in and one edge out, so edges pair up at that vertex. Only the two endpoints of an open trail can be left with an unpaired edge, which is why exactly two odd-degree vertices are allowed for a path and none for a circuit. That argument says nothing about connectivity: a graph can satisfy every degree condition and still be two separate pieces.

Worked example: refuse the one-pass snowplow plan. Streets: A-B, B-C, C-D, D-A, A-C, B-D, each 1 km. Degrees: A=3, B=3, C=3, D=3. Four odd vertices, so no Eulerian trail exists. A design promising "one truck, every street once, 6 km" is infeasible; refuse it. The fix is the Chinese Postman: pair the odd vertices by shortest path ((A,C)=1 and (B,D)=1) duplicate those edges, and the multigraph is now all-even. Route length 6+2 = 8 km. The refusal is not "Eulerian paths are bad"; it is "this plan's cost is wrong by 2 km and its route does not exist."

Conditions, including the one the degree check misses.

GraphCircuitPath
Undirectedconnected (ignoring isolated vertices) + all degrees evenconnected + exactly two odd
Directedall in=out + single SCC on non-isolated verticesone vertex out−in=1, one in−out=1, rest balanced, weakly connected

Connectivity costs O(V+E) to verify (BFS or union-find), not O(V). Two disjoint triangles pass the degree check, every vertex has degree 2, and have no Eulerian circuit. A design that checks only degrees will accept them.

Alternatives and when to refuse the model. If the requirement is "traverse every edge" (snowplow, street sweeping, network link testing, DNA fragment assembly), Eulerian/CPP is polynomial and the right tool. If it is "visit every vertex" (delivery stops, TSP), the problem is Hamiltonian and NP-hard: refuse any design that assumes an exact polynomial solution. The two are easy to conflate because both say "cover the graph once." Eulerian structure is still useful there: Christofides builds an MST, matches the odd-degree vertices, and takes the Eulerian circuit of that multigraph to get a 3/2-approximation for metric TSP.

Failure modes and detection.

  • Degree check passes, graph disconnected → BFS from one non-isolated vertex; if reachable count < non-isolated count, refuse.
  • Directed degrees balanced but not strongly connected → Tarjan/Kosaraju SCC; more than one SCC with edges, refuse.
  • Parallel edges or self-loops → self-loops add 2 to degree and never change parity; Hierholzer must consume edge objects, not adjacency entries, or it will reuse a parallel edge.
  • Wrong abstraction → ask whether the requirement is edge-covering or vertex-covering before writing any code.

Deciding criteria. Refuse when the trail's existence is load-bearing and either condition fails, when the cost model ignores required deadheading, or when the problem is vertex-covering. Otherwise the Eulerian property is what makes the design cheap: Hierholzer runs in O(E) and the whole check is linear.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain hamiltonian paths and hardness without using the usual slogan?

Answer

The 90-second version. A Hamiltonian path visits every vertex of a graph exactly once. The decision problem: does one exist?: is NP-complete, and that word carries two separate claims the slogan flattens: a proposed path is checkable in O(V+E) (it is in NP), and every problem in NP reduces to it in polynomial time (it is NP-hard). The consequence is not "no algorithm exists" but "no algorithm is known whose worst case is polynomial, and one would collapse NP into P."

Why it is hard, mechanically. There is no local certificate. Eulerian path, visit every edge once, is easy because the certificate is local: the graph is connected and 0 or 2 vertices have odd degree. Hamiltonian path has no degree condition; existence depends on global structure, so no vertex-by-vertex scan decides it.

The reduction that anchors the claim: 3-SAT ≤_p Hamiltonian cycle (Karp, 1972). Variables become chains traversed in one of two directions, clauses become gadgets enterable only when some literal is true. And Hamiltonian path ≤_p Hamiltonian cycle: add a vertex u adjacent to every vertex; G has a Hamiltonian path iff G+u has a Hamiltonian cycle, since the cycle must pass through u and deleting u leaves the path.

The exact algorithm, and where it dies. Bitmask DP: dp[S][v] is true iff some path visits exactly the vertex set S and ends at v. Transition dp[S∪{u}][u] |= dp[S][v] for each edge (v,u) with u∉S. Answer: any dp[V][v]. Time O(2^n·n²), space O(2^n·n).

Trace on G with edges 0-1, 1-2, 2-3:

base      dp[{0}][0] dp[{1}][1] dp[{2}][2] dp[{3}][3] = T
{0,1}     dp[{0,1}][1]=T (0->1)   dp[{0,1}][0]=T (1->0)
{1,2}     dp[{1,2}][2]=T (1->2)   dp[{1,2}][1]=T (2->1)
{0,1,2}   dp[{0,1,2}][2]=T (from {0,1}@1)   dp[{0,1,2}][0]=T (from {1,2}@1)
{0,1,2,3} dp[all][3]=T (from {0,1,2}@2)  -> path 0-1-2-3

Sizes: n=20 gives 2²⁰·400 ≈ 4.2×10⁸ transitions. The upper edge even in compiled code, usually too slow in Python. n=30 gives ≈9.7×10¹¹, infeasible.

ApproachGuaranteeWrong when
Bitmask DPexact, O(2^n·n²) time, O(2^n·n) spacen ≳ 22–25; memory blows before time
Backtracking + pruning (degree, connectivity, articulation points)exact, no worst-case bounddense graphs with many near-solutions
Christofides 3/23/2 for metric TSP: a different problemgraph is not metric, or you need existence, not a tour

Approximation guarantees belong to metric TSP, the optimisation problem. "Does a Hamiltonian path exist" is a decision problem; approximating it is as hard as deciding it, and general TSP has no constant-factor approximation unless P=NP.

Failure modes. Greedy nearest-neighbour returns a walk that silently skips vertices and looks correct on small inputs. LP or matching relaxations yield fractional 2-factors that do not round to a single path. And "NP-complete" does not mean "always slow": many real instances are easy, so a heuristic that passes tests can still be wrong on the adversarial case.

So: name the hardness, give the exponential bound, and state the vertex count where it stops being practical.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you solve the Travelling Salesperson Problem using dynamic programming with bit manipulation, and what is its time and space complexity?

Answer

The Travelling Salesperson Problem (TSP) is solved exactly via dynamic programming over subsets using the Bellman-Held-Karp algorithm. Instead of evaluating all $(n - 1)!$ permutations via brute force ($O(n!)$), we cache subproblem solutions indexed by a bitmask of visited vertices and the current terminal vertex. This reduces the time complexity to $O(n^2 2^n)$ and space complexity to $O(n 2^n)$.

State Representation and Recurrence

Let a graph have $n$ vertices labelled $0, \dots, n - 1$. Choose vertex $0$ as the arbitrary start and end vertex.

  • State: dp[mask][u] denotes the minimum cost of a path that starts at vertex $0$, visits precisely the set of vertices represented by the bitmask mask (where the $i$-th bit is $1$ if vertex $i$ is visited), and currently terminates at vertex $u$.
  • Base Case: dp[1 << 0][0] = 0 (only vertex 0 visited, at cost 0). All other entries initialize to $\infty$.
  • Transition: For every valid subset mask containing bit 0 and bit $u$, and for every unvisited neighbor $v$ (where (mask & (1 << v)) == 0): $$\text{dp}[\text{mask} \mid (1 \ll v)][v] = \min_{u \in \text{mask}} (\text{dp}[\text{mask}][u] + \text{weight}(u, v))$$
  • Final Answer: Return to vertex 0 from the completed tour: $$\min_{u = 1}^{n-1} (\text{dp}[(1 \ll n) - 1][u] + \text{weight}(u, 0))$$

Python 3 Implementation

Python
import math

def tsp_held_karp(dist: list[list[float]]) -> float:
    n = len(dist)
    if n <= 1:
        return 0.0

    num_states = 1 << n
    dp = [[math.inf] * n for _ in range(num_states)]
    dp[1][0] = 0.0  # Base case: visited only node 0

    for mask in range(1, num_states):
        if not (mask & 1):
            continue  # Must include starting node 0
        for u in range(n):
            if dp[mask][u] == math.inf:
                continue
            for v in range(n):
                if not (mask & (1 << v)):
                    next_mask = mask | (1 << v)
                    new_cost = dp[mask][u] + dist[u][v]
                    if new_cost < dp[next_mask][v]:
                        dp[next_mask][v] = new_cost

    full_mask = (1 << n) - 1
    return min(dp[full_mask][u] + dist[u][0] for u in range(1, n))

Complexity and Scaling Ceilings

$n$Total States ($n 2^n$)Transitions ($n^2 2^n$)Memory Footprint (64-bit float table)Feasibility
10$1.02 \times 10^4$$1.02 \times 10^5$$\approx 80\text{ KB}$Instant (< 5 ms)
16$1.05 \times 10^6$$1.68 \times 10^7$$\approx 8.4\text{ MB}$Feasible in Python (< 1s)
20$2.10 \times 10^7$$4.19 \times 10^8$$\approx 168\text{ MB}$Feasible in C++/Rust; tight in Python
24$4.03 \times 10^8$$9.66 \times 10^9$$\approx 3.2\text{ GB}$Requires compiled execution + multithreading
30$3.22 \times 10^{10}$$9.66 \times 10^{11}$$\approx 257\text{ GB}$Exceeds single-node working memory and CPU limits

Trade-offs and Failure Modes

  1. Memory Exhaustion ($n > 23$): Memory grows strictly as $\Theta(n 2^n)$. Attempting to allocate an array of $24 \times 2^{24}$ 8-byte numbers requires over 3.2 GB of contiguous memory. In systems with $n > 22$, you must either discard past layers (iterating by mask popcount) or switch to branch-and-bound (e.g., Concorde).
  2. Ignoring Metric Assumptions: Held-Karp computes the exact tour on arbitrary directed graphs. However, if the graph satisfies the triangle inequality (metric TSP) and $n > 30$, solving exactly is the wrong engineering choice; reach for Christofides' 1.5-approximation or 2-opt local search instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How does the 2-approximation algorithm for Metric TSP work, and why does the triangle inequality guarantee its bound?

Answer

Core answer (first 90 seconds). Metric TSP is TSP on a complete graph whose weights satisfy the triangle inequality $w(u,w) \le w(u,v) + w(v,w)$. The double-tree algorithm: build a minimum spanning tree $T$, duplicate every edge to get an Eulerian multigraph $2T$, walk an Euler tour, then shortcut repeated vertices. The result is a Hamiltonian cycle of cost at most $2 \cdot \text{OPT}$. Two facts give the bound: an MST costs no more than the optimal tour (drop one edge from that tour and you have a spanning tree), and shortcutting never increases cost (triangle inequality). Runtime is $O(V^2)$ with Prim on the dense graph.

Mechanism

  1. MST. Compute $T$ on $G=(V,E)$ with Prim or Kruskal. On a complete graph, Prim with an adjacency matrix is $O(V^2)$.
  2. Double. Every vertex in $2T$ has even degree, so an Euler tour $W$ exists. $\text{cost}(W) = 2,\text{cost}(T)$.
  3. Shortcut. Walk $W$ from a root; when the next vertex is already visited, jump to the next unvisited one. This is exactly a DFS preorder of $T$, closed back to the root.

Why the bound holds

Let $H^*$ be the optimal Hamiltonian cycle and $H$ the shortcut tour.

  • MST lower bound. Removing any edge $e$ from $H^$ leaves a spanning tree, so $\text{cost}(T) \le \text{cost}(H^ - e) \le \text{cost}(H^*)$.
  • Shortcutting is free. Each shortcut replaces a path $u \to v \to w$ with the edge $(u,w)$. Metric gives $w(u,w) \le w(u,v) + w(v,w)$, so cost never rises. Chaining shortcuts: $\text{cost}(H) \le \text{cost}(W) = 2,\text{cost}(T) \le 2,\text{cost}(H^*)$.
Python
# Python 3.12. Metric input: adj_matrix[i][j] satisfies triangle inequality.
def metric_tsp_2_approx(adj_matrix: list[list[float]]) -> list[int]:
    n = len(adj_matrix)
    visited = [False] * n
    key = [float("inf")] * n
    parent = [-1] * n
    key[0] = 0

    for _ in range(n):                      # Prim's MST, O(V^2) dense
        u = min((v for v in range(n) if not visited[v]), key=lambda v: key[v])
        visited[u] = True
        for v in range(n):
            if not visited[v] and adj_matrix[u][v] < key[v]:
                key[v] = adj_matrix[u][v]
                parent[v] = u

    tree = [[] for _ in range(n)]
    for v in range(1, n):
        tree[parent[v]].append(v)
        tree[v].append(parent[v])

    tour, seen = [], [False] * n
    def dfs(u: int) -> None:                # preorder == shortcutting
        seen[u] = True
        tour.append(u)
        for nxt in tree[u]:
            if not seen[nxt]:
                dfs(nxt)
    dfs(0)
    tour.append(0)
    return tour

The credible alternative: Christofides (3/2)

Christofides reuses the same MST but adds a minimum-weight perfect matching $M$ on the odd-degree vertices of $T$ (there is an even number of them). $T \cup M$ has all even degrees, so an Euler tour exists; shortcut it. Since $\text{cost}(M) \le \text{OPT}/2$, the tour costs at most $1.5,\text{OPT}$.

Double-treeChristofides
Ratio23/2
Extra stepnonemin-weight perfect matching on odd-degree vertices
Runtime$O(V^2)$ (dense Prim)$O(V^3)$ (Blossom matching dominates)
Implementation~30 linesneeds a matching library
Pick whenspeed/simplicity, large $n$, or MST already in handtighter guarantee, $n$ moderate

Deciding criteria: if the $O(V^3)$ matching is affordable and you want the 1.5 guarantee, use Christofides. If $n$ is large enough that matching is prohibitive, or you need a quick tour, double-tree. Both require the metric assumption. In practice, for large instances neither is used directly; local-search heuristics (Lin–Kernighan, 2-opt) dominate.

Failure mode: non-metric graphs

If weights violate the triangle inequality (negative edges, prohibited transitions, or toll/capacity penalties where a detour is cheaper than a direct edge), shortcutting $(u,w)$ can cost arbitrarily more than $(u,v)+w(v,w)$, and the 2 bound collapses. On general graphs, TSP has no constant-factor polynomial approximation unless $P = NP$, since deciding whether a Hamiltonian cycle exists reduces to it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does the second-shortest path force that a junior answer usually skips?

Answer

Core (first 90 seconds). "Second shortest" names two different problems, and the cheap algorithm solves only one. Two-distance Dijkstra keeps dist1[v] and dist2[v] and, on each relaxation, shifts the old best into the second slot. It runs in the same O(E log V) as plain Dijkstra, roughly a 2× constant, and returns the second-shortest walk, which may revisit vertices. If the system needs a second simple path (a failover route, a plan that must not loop), that answer is wrong, and the correct fix costs one Dijkstra per edge of the shortest path. The trade-off a junior skips: the fast method buys a constant factor and hands back a path that can repeat nodes or share edges with the primary; the correct method costs a factor of the path length. Name the semantics before choosing.

Mechanism, on a graph where it bites. Directed graph, edges S→A=1, A→T=1, A→B=1, B→A=1, S→B=10, B→T=10.

Two-distance Dijkstra:

S: d1=0
  S→A: d1[A]=1
  S→B: d1[B]=10
A(d1=1):
  A→T: d1[T]=2
  A→B: 2<10 → d2[B]=10, d1[B]=2
B(d1=2):
  B→A: 3>d1[A]=1 → d2[A]=3
  B→T: 12>d1[T]=2 → d2[T]=12
A(d2=3):
  A→T: 4<12 → d2[T]=4
  A→B: 4<10 → d2[B]=4
B(d2=4): B→T: 14>4, no change

dist2[T]=4, path S-A-B-A-T: it visits A twice. The second-shortest simple path is S-A-B-T = 12. Same graph, answers 4 and 12.

Alternatives and their cost. Yen's algorithm enumerates loopless paths: for K=2 it runs a Dijkstra per spur node along the shortest path, so about one Dijkstra per hop; worst case O(K·V·(E + V log V)) and it scales to arbitrary K. Deleting each edge of the shortest path and rerunning Dijkstra gives the second simple path exactly, the second simple path must avoid at least one edge of the first, at one Dijkstra per edge, and it only ever answers K=2.

Concrete figures. V=10,000, E=50,000, average shortest path 15 hops, binary-heap Dijkstra ≈5 ms: two-distance ≈10 ms; edge-deletion ≈15 runs ≈75 ms; Yen's K=2 ≈75 ms, and K=10 with 15-hop paths ≈750 ms.

Failure modes.

  • Walk returned where a simple path was required. Detection: assert the path has no repeated vertex. The trace above fails on A. Cost: an infeasible route.
  • Backup shares an edge with the primary. "Second shortest" does not mean disjoint; the second path can reuse the primary's links, so it fails when they fail. Detection: intersect the two edge sets; non-empty means the backup isn't a backup. Cost: a failover that fails over to the same broken link.
  • Ties collapse. With strict < and d != dist1[v], equal-cost alternatives leave dist2[T] == dist1[T]. Detection: check that equality; if true, the "second" path is a tie, not a longer path.

Define path semantics first, then pick: two-distance relaxation for walks, Yen's or edge-deletion for simple paths.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about dynamic connectivity?

Answer

The belief. For a stream of edge insertions and deletions with connectivity queries, my default is offline dynamic connectivity: read the whole sequence, build a segment tree over time where each edge occupies the O(log Q) nodes covering its live interval, then DFS that tree with a rollback DSU. Union by rank, no path compression, so each union can be undone. It runs in O((N + Q) log Q) and is far less code than a fully dynamic structure like Holm–de Lichtenberg–Thorup at O(log² n) amortized per operation. The belief under test is that the offline structure earns its complexity over just rebuilding on demand.

The smallest experiment. One timing on the real trace, not a synthetic one. Run two implementations at the actual N and Q:

  • A: rebuild the DSU from scratch on every query. O(Q · N · α(N)).
  • B: the offline segment tree plus rollback DSU.

If A finishes inside your budget at the real sizes, B is unjustified and you ship A. One trace, two timings, one comparison. No new infrastructure, no load generator.

Python
# A: rebuild per query (Python 3.11)
def rebuild_per_query(n, ops):
    live, out = set(), []
    for op in ops:
        if op[0] == 'add':   live.add((op[1], op[2]))
        elif op[0] == 'del': live.discard((op[1], op[2]))
        else:
            p = list(range(n))
            def find(x):
                while p[x] != x:
                    p[x] = p[p[x]]; x = p[x]
                return x
            for u, v in live:
                ru, rv = find(u), find(v)
                if ru != rv: p[ru] = rv
            out.append(find(op[1]) == find(op[2]))
    return out

# B: segment tree over time + rollback DSU
def offline(n, ops):
    start, intervals = {}, []
    for t, op in enumerate(ops):
        if op[0] == 'add':   start[(op[1], op[2])] = t
        elif op[0] == 'del':
            k = (op[1], op[2]); intervals.append((start.pop(k), t, *k))
    T = len(ops)
    for (u, v), l in start.items(): intervals.append((l, T, u, v))
    size = 1
    while size < T: size *= 2
    tree = [[] for _ in range(2 * size)]
    for l, r, u, v in intervals:
        l += size; r += size
        while l < r:
            if l & 1: tree[l].append((u, v)); l += 1
            if r & 1: r -= 1; tree[r].append((u, v))
            l >>= 1; r >>= 1
    parent, rank, hist = list(range(n)), [0] * n, []
    def find(x):
        while parent[x] != x: x = parent[x]
        return x
    def union(u, v):
        ru, rv = find(u), find(v)
        if ru == rv: hist.append(None); return
        if rank[ru] < rank[rv]: ru, rv = rv, ru
        parent[rv] = ru
        bump = rank[ru] == rank[rv]
        if bump: rank[ru] += 1
        hist.append((rv, ru, bump))
    def rollback():
        h = hist.pop()
        if h is None: return
        rv, ru, bump = h
        parent[rv] = rv
        if bump: rank[ru] -= 1
    ans = [None] * T
    def dfs(node):
        for u, v in tree[node]: union(u, v)
        if node >= size:
            t = node - size
            if t < T and ops[t][0] == 'query':
                ans[t] = find(ops[t][1]) == find(ops[t][2])
        else:
            dfs(2 * node); dfs(2 * node + 1)
        for _ in tree[node]: rollback()
    dfs(1)
    return ans

Worked trace. n = 4, ops = add(0,1), add(2,3), query(0,1), del(0,1), query(0,1), query(2,3). T = 6, size = 8.

edgelive interval [l, r)segment-tree nodes
(0,1)[0, 3)4 (t=0..1), 10 (t=2)
(2,3)[1, 6)9 (t=1), 5 (t=2..3), 6 (t=4..5)

DFS: node 4 unions (0,1); node 9 unions (2,3) then rolls back; node 10 unions (0,1) on top of node 5's (2,3), and find(0) == find(1) is True at t=2. Node 6 holds (2,3); at t=4 find(0)=0, find(1)=1 → False; at t=5 find(2)=find(3)=2 → True. Queries at t=2,4,5 return True, False, True.

Worked arithmetic (hypothetical).

NQA: rebuild per queryB: offlineverdict
10^510^5~10^10 DSU ops, minutes~3×10^6, millisecondsB
10^510^3~10^8, under a second~10^6A

The variable that decides it is Q relative to N, not the deletion fraction.

The even smaller experiment. Before timing anything, count deletions in the trace. If the count is zero, plain union-find with path compression is O(N α(N)) total and the question is moot. One pass over the input settles it.

What would mislead the experiment. Timing on synthetic input whose deletion rate and query mix differ from production: B's cost scales with the number of live intervals, so a trace with few deletions understates B and makes A look better than it is. Timing at the wrong scale: A is quadratic in N, so a 10^3-edge microbenchmark says nothing about the 10^5-edge workload. And measuring only the structure's own time while ignoring the cost of materialising the segment tree, which is O(N log Q) memory and can dominate at large N.

When the belief is right. When deletions are frequent and Q is large relative to N, offline dynamic connectivity is the correct default and the experiment confirms it. When deletions are rare or Q is small, a periodic full rebuild (rebuild the DSU every k updates, answer queries from the current copy) is simpler still and often within a constant factor of B. Reach for the offline structure only when the measurement says the naive path is out of budget.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How do graph processing frameworks partition and traverse graphs that exceed single-machine memory?

Answer

Core answer. Two decisions, made independently: how the graph is cut across machines, and how computation moves over the cut.

Partitioning. Edge-cut assigns vertices to partitions and cuts the edges between them; vertex-cut assigns edges and replicates high-degree vertices. On power-law graphs edge-cut is the wrong default: a hub of degree $10^6$ sitting in one partition sends almost every message across the network. Vertex-cut bounds replication instead of letting degree bound it: GraphX's EdgePartition2D lays edges on a $\sqrt{P}\times\sqrt{P}$ grid, guaranteeing a $2\sqrt{P}$ bound on vertex replication (P=64 → at most 16 copies of any vertex, whatever its degree).

Traversal. Pregel-style BSP: each superstep is compute → send along out-edges → barrier → vote to halt. Cost per superstep is one network round trip plus a barrier, and the superstep count is bounded by the graph's hop diameter, not by $|V|$. That makes BSP fine for PageRank (fixed iteration count) and bad for BFS on a road network (diameter in the thousands).

Single machine. GraphChi's Parallel Sliding Windows keeps vertex state in RAM and streams edges from disk in $P$ sequential passes, turning random pointer chasing into sequential I/O.

Before any of that: check the size. 1B edges in CSR (8-byte offsets + 4-byte dst + 4-byte weight) is ~8.8 GB: a 32 GB box holds it. Clusters are for graphs that don't fit, not for graphs that sound big.

Partitioning

Edge-cutVertex-cut
Unit assignedverticesedges
Hub vertexcut across up to $P$ partitionsreplicated at most $2\sqrt{P}$ times
Bottleneckcross-partition traffic, memory skewmirror synchronization, more vertex state
ImplementationsMETIS/ParMETIS (offline), hash (streaming)PowerGraph greedy/oblique, GraphX EdgePartition2D
Good formeshes, low-degree graphspower-law graphs

With $P=64$ and a hub of degree $10^6$, edge-cut puts roughly $10^6 \cdot 63/64$ edges across partition boundaries; EdgePartition2D caps that vertex at 16 replicas. That is the whole argument, and it is why GraphX defaults to a vertex-cut strategy for social and web graphs.

Traversal: BSP supersteps

Python
# Pregel-style SSSP, single-process simulation of the BSP loop. Python 3.11.
from collections import defaultdict

edges = {0: [(1, 1.0), (2, 4.0)],
         1: [(2, 1.0), (3, 5.0)],
         2: [(3, 1.0)],
         3: []}
dist = {v: float("inf") for v in edges}
dist[0] = 0.0
active = {0}
step = 0
while active:
    outbox = defaultdict(list)
    for v in active:                      # compute + send
        for u, w in edges[v]:
            outbox[u].append(dist[v] + w)
    active = set()                        # barrier: all messages delivered
    for u, msgs in outbox.items():        # receive
        m = min(msgs)
        if m < dist[u]:
            dist[u] = m
            active.add(u)
    step += 1
    print(step, {k: dist[k] for k in sorted(dist)}, sorted(active))

Output, traced superstep by superstep:

1 {0: 0.0, 1: 1.0, 2: 4.0, 3: inf} [1, 2]
2 {0: 0.0, 1: 1.0, 2: 2.0, 3: 5.0} [2, 3]
3 {0: 0.0, 1: 1.0, 2: 2.0, 3: 3.0} [3]
4 {0: 0.0, 1: 1.0, 2: 2.0, 3: 3.0} []

Two things this trace shows. First, messages are computed from the state at the start of the superstep: vertex 2 still holds 4.0 in superstep 2, so vertex 3 receives 5.0 and only gets the correct 3.0 in superstep 3. Second, a 4-vertex path takes 4 supersteps: hop diameter (3) plus one no-op round to confirm halting. On a road network with diameter in the thousands, that is thousands of barriers.

Single machine: out-of-core

GraphChi (OSDI '12) splits vertices into $P$ intervals by ID, sized so the edges incident to each interval fit in RAM. Every edge is stored twice on disk: once sorted by source, once sorted by destination. For interval $i$, the sliding window loads edges with destination in $i$ plus edges with source in $i$. A full pass reads each shard file sequentially once: $2|E|$ sequential reads, zero seeks, while vertex state ($|V| \times$ state size) stays resident. X-Stream (OSDI '13) takes the edge-centric version: stream edges, scatter-gather, no vertex state in RAM, at the cost of re-reading edges.

Failure modes and how to detect them

  • Barrier straggler. One partition holds a hub; every other worker idles. Detect: per-superstep wall time per worker, and max/median partition edge count. Fix: vertex-cut, or PowerLyra's hybrid (vertex-cut for hubs, edge-cut for the rest).
  • Message buffer OOM. A hub receives one message per neighbor in a single superstep. Detect: peak outbox size per superstep. Fix: Pregel's combiner merges messages to the same target before sending (min for SSSP); Giraph exposes message limits.
  • Checkpoint cost. Pregel checkpoints vertex state each superstep. 1B vertices × 100 B = 100 GB per checkpoint. Detect: checkpoint write time as a fraction of superstep time. Fix: checkpoint every $k$ supersteps, or use a lineage-based system (GraphX on Spark RDDs).
  • Diameter blowup. Superstep count tracks hop diameter. Detect: superstep count vs. $|V|$. Fix: single-machine out-of-core engine, or direction-optimizing BFS (Beamer et al.), which switches to bottom-up traversal once the frontier covers most vertices.

When not to distribute

If the graph fits in RAM, a single-machine engine (Ligra, GAP, or plain CSR in C++) beats a cluster on every metric that matters: no serialization, no barrier, no network. Reach for Pregel/Giraph/GraphX when the graph genuinely exceeds one machine's memory, or when the data already lives in HDFS and the graph computation is one stage of a larger pipeline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does problem reductions interact with rollback, and where do people ignore that?

Answer

A reduction preserves the forward objective and discards the cost of undoing a step. Rollback is that cost. So a reduction is usually valid for "solve this" and quietly invalid for "solve this, then undo part of it and re-solve", which is what rollback asks for. The mapping between the problem's objects and the standard formulation almost never includes inverse operations, and that omission is the whole failure.

ReductionForward costWhat rollback actually costsWhere it breaks
Task DAG → topological sortO(V+E)undo adds edges; undo edges can create a cyclethe acyclicity precondition fails
Assignment → bipartite matchingHopcroft–Karp, O(E√V)deleting an edge can drop the matching below maximum; needs re-augmentation"undo = delete the edge" is wrong
Disconnect a network → min cutDinic, O(V²E)the cut is global; restoring one link changes the whole cutno local undo exists
Connectivity → union-findα(n) amortizedpath compression is not reversiblemust drop path compression

The last row is the one that bites in code. Union-find with path compression is amortized α(n), but you cannot undo a union: path compression rewrote parent pointers you never recorded. Rollback DSU drops path compression, keeps union by size, and pushes each union onto a stack.

Python
# Python 3.12
class RollbackDSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.history = []          # (child, new_root, size_of_root_before)

    def find(self, x):             # O(log n): no path compression
        while self.parent[x] != x:
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            self.history.append(None)
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.history.append((rb, ra, self.size[ra]))
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True

    def snapshot(self):
        return len(self.history)

    def rollback(self, snap):
        while len(self.history) > snap:
            rec = self.history.pop()
            if rec is not None:
                child, root, old_size = rec
                self.parent[child] = child
                self.size[root] = old_size

Trace on n=4. union(0,1): sizes equal, push (1,0,1), parent[1]=0, size[0]=2. union(2,3): push (3,2,1), parent[3]=2, size[2]=2. Take snap = 2. union(1,3): find(1) walks 1→0, find(3) walks 3→2; sizes 2 and 2, push (2,0,2), parent[2]=0, size[0]=4. Now rollback(2) pops (2,0,2), sets parent[2]=2 and size[0]=2. find(3) walks 3→2 and stops: components are {0,1} and {2,3}, exactly the pre-union state. Depth stays ≤ log₂n because union by size alone bounds it.

Where people ignore the gap:

  • Assuming undo is O(1) because the forward op was. Deleting an edge from a maximum matching leaves it maximum or one short; you must re-augment, which is not the reverse of the augmenting path you took.
  • Assuming re-optimization after undo is cheap. Dynamic connectivity is a different algorithm from re-solving: Holm–de Lichtenberg–Thorup gives O(log²n) amortized per edge update, versus recomputing a min cut from scratch.
  • Assuming idempotency. A retry after a rollback double-applies a compensation: a refund issued twice. Guard with idempotency keys and a reconciliation job that compares intended against applied state.

Detect the DSU class of bug with a property test: run random union/rollback sequences against a brute-force BFS component count and assert equality. If rollback frequency is comparable to forward-op frequency, a batch reduction is the wrong tool: pick a formulation that is incrementally maintainable instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites verifying graph algorithms but cannot apply it?

Answer

The question I'd ask

"Here's a directed graph: A→B weight 1, A→C weight 2, C→B weight −2. Run Dijkstra from A, tell me the distance it reports to B, then tell me the true shortest distance."

That's the whole question. No preamble about invariants. Someone who has only memorised "Dijkstra needs non-negative weights" says "Dijkstra doesn't apply" and stops. Someone who can apply it runs the algorithm and shows me the wrong number.

What a strong answer looks like

dist[A]=0, dist[B]=dist[C]=∞. Pop A. Relax A→B → dist[B]=1; relax A→C → dist[C]=2. Pop B (smallest, 1) and finalise it. Pop C, relax C→B: 2 + (−2) = 0 < 1, but B is already finalised, so the update is discarded. Dijkstra reports dist[B]=1. The true shortest path is A→C→B = 0.

The number isn't the point. The point is whether they can say why: Dijkstra's correctness rests on the invariant that a popped vertex already holds its final distance, which holds only because every relaxation is non-decreasing. A negative edge breaks that, and the failure is silent: no exception, just a wrong answer.

Second question, same shape

"Here's Floyd-Warshall with the k loop innermost instead of outermost. Give me an input where it returns a wrong answer."

A strong candidate constructs one: vertices 0,1,2,3; edges 0→3 (1), 3→2 (1), 2→1 (1). The correct distance 0→1 is 3. With k innermost, row 0 runs once, j ascending. At j=1, d[0][2] is still ∞ (it needs d[0][3]+d[3][2], only computed when j=2) and d[3][1] is still ∞ (row 3 hasn't run yet), so d[0][1] stays ∞, and row 0 is never revisited. The algorithm returns ∞.

The invariant they should name: the outer k loop guarantees that when k is processed, every path whose intermediate vertices are all < k is already final. Move k inward and that guarantee is gone.

What I'm actually scoring

  • Do they produce a counterexample, or restate the rule? "Dijkstra needs non-negative weights" is exactly the recitation I'm trying to get past.
  • Do they trace it correctly, including the finalisation step that causes the wrong answer?
  • Can they name the invariant that breaks, not just the symptom?

If they freeze, I shrink the instance, a two-node graph with one negative edge, to separate "can't apply" from "nervous at a whiteboard."

Alternatives, and when they're better

Handing them a buggy implementation and asking for the failing input tests the same skill with less setup, and it's the version I'd use if I'm short on time. Property-based testing (Hypothesis, QuickCheck) is the production form of this: generate small random graphs, compare against a brute-force reference. That's the right tool for verifying your own code, but it's a weaker interview probe, because the framework does the counterexample search the candidate is supposed to be doing by hand.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document knowing when to stop so the next owner can operate it?

Answer

The 90-second answer. A stopping criterion is only operable if the doc carries the boundary, not the conclusion. "This is NP-hard, we approximate it" is not a handover: the next owner can't tell whether to stop or keep searching. I'd leave a decision record with four fields: the hardness result and where it came from, the instance size at which the exact method stops fitting the latency budget, the approximation with its proven ratio and the precondition that makes the ratio hold, and the measurement that would falsify the threshold. Then "stop" is a number they can check, not a judgement they have to re-derive.

The record itself.

FieldExampleWhy the next owner needs it
HardnessTSP is NP-hard; no poly-time exact algorithm knownTells them not to spend a sprint looking for one
Exact thresholdHeld-Karp O(n²2ⁿ) fits ≤ ~22 cities at p99 < 5 sThe number that decides exact vs approximate
ApproximationChristofides, 3/2 ratio, metric instances onlyRatio is void if the distance matrix violates the triangle inequality
Falsifierp99 > 5 s at n=22, or non-metric inputs appearThe trigger to re-open the decision

Where the threshold comes from. Held-Karp is O(n²2ⁿ) time. On a machine doing ~10⁸ DP transitions per second (hypothetical: measure yours): n=20 → 2²⁰·400 ≈ 4.2×10⁸ ≈ 4 s; n=24 → 2²⁴·576 ≈ 9.7×10⁹ ≈ 97 s; n=28 → 2²⁸·784 ≈ 2.1×10¹¹ ≈ 35 min. So the doc says "exact up to 22, approximate above" and shows the arithmetic, because the next owner's hardware will differ and they need to redo it, not trust it.

Make the boundary fire. The record is only operable if the code enforces it:

Python
# Python 3.12; held_karp and christofides are the two implementations named in the record
EXACT_MAX_N = 22          # from the decision record; re-measure on new hardware

def solve(dist):
    n = len(dist)
    if n <= EXACT_MAX_N:
        return held_karp(dist)          # exact, O(n^2 2^n)
    assert is_metric(dist), "Christofides 3/2 bound requires metric input"
    return christofides(dist)           # 3/2-approx, ratio valid only if metric

The assert is the documentation doing work: a non-metric instance trips it instead of silently returning a result with no guarantee.

Failure modes. The record rots in two ways. First, the threshold is copied without the hardware assumption, so a migration to slower nodes makes "exact up to 22" false: detect by logging instance size and solve time, and alert when p99 crosses the documented budget. Second, the ratio is quoted without its precondition; someone feeds a non-metric matrix and reports "within 3/2" when nothing bounds it: detect with the assert above, and log the achieved ratio against the proven one (a correct implementation never exceeds it; exceeding it means a bug, not a better result).

When this framing doesn't apply. If the problem is actually polynomial and the team just hasn't found the structure (bounded treewidth, acyclicity, a DAG) the record should say that instead, because "NP-hard" would wrongly close the search. The record's job is to make the boundary checkable, not to end the conversation.

Curated: · Written: · Reviewed:

Difficulty: Hard