Skip to content
Tech Interview Prep
Technical interview guide

Graphs

Nodes and edges generalizing trees to arbitrary connections: cycles, multiple parents, and disconnected components all allowed.

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

Scope: Language-neutral, with container costs cited from CPython 3.14.

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-1

Explain modelling a problem as a graph and how it changes a production decision.

Answer

The 90-second answer

Modelling a problem as a graph is a decision about what a vertex is, and that decision is what changes the production call: usually from "which algorithm" to "can this be precomputed, or must it run per request."

A vertex is a state; an edge is a legal transition. The same physical objects produce different graphs depending on the question you ask, so you name one vertex in a sentence before choosing an algorithm. Once you have, the vertex and edge counts set the cost, and the cost is what decides the production question.

Worked example: service dependency graph. 400 services, 1,800 directed edges. The question is "if service X degrades, which services are affected?": reachability. BFS from one vertex is O(V+E) = 2,200 steps, microseconds. But you need it for every service, during an incident, while health checks run at 5k rps. Full transitive closure is 400 × 2,200 = 880,000 steps, roughly 1–3 ms in Go, and the result is 400 bitsets of 400 bits = 20 KB. That settles the production decision: precompute the closure on every deploy, store the bitsets, answer per request with a bitmask AND. Without the graph framing you write a recursive "walk the dependencies" function and meet its cost for the first time mid-incident.

The modelling choice is the trade-off.

ModelVertexEdgeCostReach for it when
Adjacency listservicedependencyO(V+E) BFS, O(V+E) memorySparse; reachability, shortest path
Adjacency matrixservicedependencyO(V²) memory, O(1) edge testDense; you test edges far more than you traverse
State-space(position, budget)one legal moveV = product of dimensionsThe constraint is part of the state

State-space is where the vertex count bites. "Fewest moves from A to B carrying at most 3 keys" on a 100×100 grid:

Python
# Vertex is not the cell; it is (row, col, keys_held).
# 100x100 cells x 2^3 key subsets = 80,000 vertices.
start = (0, 0, frozenset())

80,000 vertices is trivial. Add a second budget, say fuel up to 50, and it is 10,000 × 8 × 51 = 4.08M vertices, which changes the answer from "BFS per request" to "precompute or bound the budget." The vertex definition, not the algorithm, moved the decision.

When not to model as a graph. If the relation is a total order or a tree, a graph library is overhead: a sorted list or a tree walk is simpler and faster. If edges change per request, precomputation is invalid and you pay the traversal every time, then the decision is whether to cache, not which algorithm.

Failure modes. State-space explosion, as above, detected by logging |V| before you run. Assuming a DAG when the graph has cycles: a naive DFS recurses forever or a topological sort raises, detected by a cycle check at build time. Stale precomputation: the closure is computed on deploy, so a runtime dependency change (feature flag, dynamic routing) silently invalidates it. Detected by versioning the closure against the deploy and alerting on mismatch.

So the production decision is: define the vertex, count V and E, and let that count choose precompute versus per-request. Correctness first, then the cost model the count implies.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Walk through complexity in terms of V and E, including where engineers most often get it wrong.

Answer

The 90-second answer

Traversal is Θ(V + E) because BFS and DFS touch each vertex once and scan each edge once. Concretely, with an adjacency list: the outer loop runs V times, and the inner loop over a vertex's neighbours runs deg(v) times. Summing over all vertices gives Σdeg(v) = 2E for an undirected graph (E for directed), so the total is Θ(V + E). The V term is bookkeeping: the visited array and the queue or stack; the E term is the edge scans.

The reason to keep both parameters is that E is not independent of V. For a simple undirected graph, 0 ≤ E ≤ V(V−1)/2. So Θ(V + E) is Θ(V) when the graph is sparse (E = O(V)) and Θ(V²) when it is dense (E = Θ(V²)). "Linear time" only means something once you say linear in what.

Where it goes wrong

  1. Quoting "O(V+E) is linear" without stating E's growth. On a dense graph that is quadratic in V.
  2. Using an adjacency matrix. Traversal becomes Θ(V²) regardless of density, because finding a vertex's neighbours means scanning a full row of V entries. On a sparse graph that is asymptotically worse than the list.
  3. Forgetting undirected edges are stored twice: Σdeg = 2E, so the constant is 2, not 1. The bound is unchanged; your step counts are not.

Adjacency list vs matrix

Adjacency listAdjacency matrix
SpaceΘ(V+E)Θ(V²)
Traverse (BFS/DFS)Θ(V+E)Θ(V²)
Edge (u,v) exists?O(deg(u))O(1)
Iterate neighbours of uO(deg(u))O(V)

Reach for the matrix only when the graph is dense (E close to V²) or you need O(1) edge queries and V is small enough that V² fits in memory.

Worked numbers

  • Road network: V = 1,000,000, E ≈ 3,000,000 (average degree 6). List traversal ≈ V + 2E = 7M steps. As a matrix, traversal is V² = 10¹² steps, and the matrix itself is 10¹² bits ≈ 125 GB.
  • Near-complete social graph: V = 10,000, E = 50,000,000 (average degree ≈ 10,000). List traversal ≈ V + 2E ≈ 100M steps. Matrix traversal = V² = 10⁸ = 100M steps: comparable here, which is exactly the dense case where the matrix stops being a liability.

Failure modes to name

  • Assuming E = O(V). True for trees and planar graphs; false for follower graphs, dense similarity graphs, and complete graphs.
  • Reporting a single n. Saying O(n) has hidden the assumption that E = O(V).
  • Benchmarking on a sparse test graph and shipping to a dense one.

What to say

Give the bound as Θ(V + E), then state E's growth for the graph in front of you: "sparse, E ≈ 6V, so effectively linear in V" or "dense, E ≈ V²/2, so quadratic." That is the whole answer.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

How would you reason about adjacency list versus adjacency matrix in a system you own?

Answer

What I'd say first

Before choosing, I'd pin down three things: which operation dominates the workload, how V and E are sized and how they change, and the memory budget of the box it runs on. Then the default is the adjacency list; I'd switch to a matrix only when the graph is genuinely dense or when the algorithm needs O(1) edge-existence queries.

Mechanism

RepresentationMemoryedge(u,v)?neighbours of u
ListO(V + E)O(deg u) unsorted; O(log deg u) sorted; O(1) expected with a per-vertex hash setO(deg u)
MatrixO(V²)O(1)O(V)

Traversal iterates neighbours, which is the operation the matrix does worst.

Arithmetic

Directed graph, V = 10,000, E = 50,000 (density 0.0005), int32 vertex ids:

  • list: 4E + 4V = 200,000 + 40,000 = 240 KB
  • matrix as bitset: V²/8 = 12.5 MB
  • matrix as byte array: V² = 100 MB

Crossover for the bitset is V²/8 = 4E + 4V, i.e. E ≈ V²/32: about 3% density. For a byte matrix it is E ≈ V²/4, 25% density. Below that the matrix is pure overhead. On neighbour iteration the gap is worse: a full BFS on the matrix reads V² = 10⁸ cells, while the list touches 2E = 10⁵ entries.

Failure modes

  1. Sparse graph on a matrix: memory. A 1,000,000-vertex follow graph with 5,000,000 edges: byte matrix 10¹² B = 1 TB, bitset 125 GB, list 24 MB. Detection: compute V²/8 before choosing, and alert on process RSS against graph size. Cost: OOM at load, or a machine provisioned 40× larger than the data needs.

  2. Traversal cost. BFS or a PageRank iteration on a matrix is O(V²) regardless of E. Detection: time one iteration and check whether it scales with E or with V². Cost: a nightly job that should take 2 minutes takes 30+.

  3. Edge weights and multigraphs. A matrix needs a parallel weight matrix, doubling memory, and cannot hold parallel edges. Detection: schema review before the first load.

  4. Vertex growth. Matrix insert/delete is O(1), but adding a vertex is a full V² copy; list append is amortised O(1). Detection: watch reallocation pauses as V grows.

When the matrix wins

Dense graphs, Floyd–Warshall, transitive closure, and bitset reachability where a row OR is a few machine words. Triangle counting and other dense linear-algebra kernels also favour it.

Alternatives worth naming

CSR (compressed sparse row) gives list asymptotics with contiguous memory and no pointer chasing, at the cost of immutability: good for a graph built once and queried many times. A hybrid keeps a bitset matrix for a dense core and lists for the sparse tail. If edge queries dominate and the graph is sparse, a per-vertex hash set buys O(1) expected lookup at roughly 2–3× the list's memory.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does breadth-first search and shortest paths guarantee, and what does it deliberately leave open?

Answer

The guarantee. Run BFS from a source s on a graph where every edge counts the same. The first time a vertex v is discovered, dist[v] is the minimum number of edges on any s → v path, and the parent pointers form a shortest-path tree: walking parents from v back to s yields a path with exactly dist[v] edges. That is the whole guarantee: distance measured in edges, plus one path that achieves it.

Why it holds. The queue is FIFO, so vertices leave it in nondecreasing distance order. When u is dequeued at distance d, every unvisited neighbour is assigned d + 1 and enqueued. No vertex at distance ≤ d is still undiscovered, so nothing can reach v later with fewer edges. Induction on dequeue order.

What it leaves open. Two things.

Which shortest path. Ties are broken by adjacency iteration order, not by anything meaningful. Trace this:

Python
from collections import deque

adj = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
src = 'A'
dist = {src: 0}
parent = {src: None}
q = deque([src])
while q:
    u = q.popleft()
    for v in adj[u]:
        if v not in dist:
            dist[v] = dist[u] + 1
            parent[v] = u
            q.append(v)

Step by step: pop A (d=0), discover B and C at d=1, queue [B, C]. Pop B (d=1), discover D at d=2, parent['D'] = 'B', queue [C, D]. Pop C (d=1); D is already in dist, so it is skipped. Pop D. Result: dist['D'] == 2, parent['D'] == 'B'. Now change adj['A'] to ['C', 'B'] and rerun: same distance, parent['D'] == 'C'. BFS pins the length, not the route.

Cost. BFS has no notion of weight. On a graph where A → B costs 100 and A → C → B costs 2, BFS returns A → B: one edge, cost 100, versus two edges, cost 2. Fewest edges is not cheapest.

Failure mode. Feeding a weighted graph to BFS yields the fewest-edge path, which is usually not the cheapest. It survives casual testing because small hand-built fixtures often have uniform weights, or the fewest-edge path happens to also be cheapest. Detect it by asserting dist[v] equals the minimum summed weight over all paths on a fixture with a deliberately non-monotone weight, or by diffing BFS output against Dijkstra on the same graph in a test.

Choosing. Unweighted or all-equal weights: BFS. Weights in {0, 1}: 0-1 BFS with a deque, pushing 0-weight neighbours to the front and 1-weight to the back. Non-negative weights: Dijkstra. Negative edges: Bellman-Ford, because Dijkstra's greedy settle is wrong once an edge can reduce a distance already finalised.

One more constraint worth naming: BFS holds the whole frontier in memory, up to O(V) vertices. On a high-branching graph the frontier, not the visited set, is what blows the budget: bidirectional BFS cuts that frontier roughly in half when both endpoints are known.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe marking visited at enqueue time and the evidence you would collect before relying on it.

Answer

In BFS, mark a vertex visited when you enqueue it, not when you dequeue it. The code below is Python 3.11:

Python
from collections import deque

def bfs(adj, start):
    seen = {start}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                q.append(v)

If you mark at dequeue, a vertex can be enqueued multiple times before it is dequeued. Trace this graph: vertices 0,1,2,3; undirected edges (0,1), (0,2), (1,2), (2,3); start 0.

Dequeue-time marking (with the required if u in seen: continue after popping):

  • q=[0], seen={}
  • pop 0, add 0. neighbors 1,2 -> q=[1,2]
  • pop 1, add 1. neighbors 0,2 -> 0 seen, 2 not seen -> q=[2,2]
  • pop 2 (first), add 2. neighbors 0,1,3 -> 0,1 seen, 3 not seen -> q=[2,3]
  • pop 2 (second), already seen, skip
  • pop 3, add 3.

Vertex 2 is enqueued twice. Enqueue-time marking enqueues each vertex once. On a complete graph K_n, dequeue-time marking enqueues each vertex once per incoming edge that is processed before it is dequeued, giving O(n^2) enqueues and a queue that can hold O(n^2) entries. For n=10,000 that is tens of millions of enqueues and queue entries, versus 10,000 enqueues and a queue of at most 10,000. The traversal order is still correct, so the defect is memory and time, not wrong output.

Before relying on enqueue-time marking, collect:

  1. Enqueue count per vertex. Instrument the loop: enqueue_count[v] += 1 right before q.append(v). Assert every count is 1. This catches duplicate enqueues directly.

  2. Peak queue length. Track max_q = max(max_q, len(q)). On a graph with V vertices, expect max_q ≤ V. If it approaches V^2/2, the marking is at dequeue.

  3. Wall time and peak RSS on a dense graph. Run BFS on K_10,000 with both marking strategies. Enqueue-time is O(V+E) time and O(V) memory; dequeue-time is O(V+E) time but O(E) memory. Measure RSS with resource.getrusage(resource.RUSAGE_SELF).ru_maxrss before and after. The difference should be visible: ~10k entries vs tens of millions.

  4. A regression test that fails if the marking moves. Build a complete graph, run BFS, assert no vertex is enqueued twice. This test is cheap and catches the defect in CI.

  5. Production telemetry. Log queue depth and enqueue counts. Alert if queue depth exceeds 2*V or if any vertex is enqueued more than once. This catches the defect on real traffic where the graph is dense.

The guarantee is that enqueue-time marking bounds the queue by V. The evidence is the enqueue count assertion and the peak queue length measurement. Without those, you're relying on the happy path.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

When is depth-first search the right traversal for a graph problem, and when is breadth-first search the better tool?

Answer

Start from the shape of the answer you owe the caller, not the shape of the graph.

If the answer is counted in edges: fewest hops, minimum steps, anything where one path can be strictly better than another: take breadth-first search. Its queue drains vertices in order of distance from the source, so the first time it reaches a vertex is via a minimum-edge path, and you can stop at a depth bound or when the target is dequeued. If the answer is about structure: reachability at all, connected components, a cycle anywhere in the graph, an ordering that satisfies dependencies, or a search where each branch carries a partial solution that gets extended and pruned: take depth-first search. DFS leaves behind pre-order and post-order, and that ordering encodes nesting; BFS leaves behind distances. Both are O(V + E) on adjacency lists, so the asymptotics never decide this.

What DFS leaves behind is why it wins on structure. Reverse post-order of a DFS over a DAG is a topological order, which is why dependency resolution is a DFS problem and not a BFS one:

Python
def reverse_post_order(adj):
    seen, post = set(), []
    for root in adj:
        if root in seen:
            continue
        seen.add(root)
        stack = [(root, iter(adj[root]))]
        while stack:
            u, it = stack[-1]
            for v in it:
                if v not in seen:
                    seen.add(v)
                    stack.append((v, iter(adj[v])))
                    break
            else:
                post.append(u)      # u is finished
                stack.pop()
    return post[::-1]               # topological order when adj is a DAG

The same nesting is what makes backtracking work: DFS holds one branch's partial state at a time and throws it away on unwind, so permutations, constraint searches and grid enumerations are DFS-shaped. BFS would have to hold every partial branch in the frontier simultaneously.

Memory is the second half of the judgement, and it turns on graph shape rather than size. Take 1,000,000 vertices:

graphDFS memoryBFS memory
a chain of 10^610^6 stack entriesfrontier of 1–2
a star with 10^6 leaves2–3 stack entriesfrontier of 10^6

So "DFS is cheap on memory" and "BFS is cheap on memory" are both false as stated. The real differences: BFS's queue is bounded by the widest level, DFS's stack by the deepest path, and recursive DFS adds a hard ceiling that the queue never has. CPython's default recursion limit is 1000 frames, so a chain-shaped graph of a few thousand vertices raises RecursionError at the start of the run. sys.setrecursionlimit moves that ceiling but trades a clean exception for the risk of exhausting the C stack, so for untrusted or unbounded depth I write the explicit stack version.

The trap I look for: someone answers "fewest servers to restart" with DFS because DFS was already on their mind. They get a path, a correct path, just not the shortest one, and it passes every test whose fixture is small enough that the two coincide.

So before writing code I name the output. Distance or hops: BFS (Dijkstra or 0-1 BFS the moment weights differ). Structural property or derived order: DFS. Unbounded depth or adversarial input: iterative DFS. If I can't say which of those the caller needs, that's the part of the problem that isn't understood yet.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does recursion depth in depth-first search matter, and where is it irrelevant?

Answer

Core answer. Recursion depth matters exactly when the height of the DFS tree, the longest path the search is currently exploring, can approach the language's stack limit. It is irrelevant when that height is bounded by a small constant, or when recursion has been replaced by an explicit stack, because then depth costs heap instead of stack.

Height is not vertex count. A star with 10,000 vertices has DFS depth 1. A chain with 10,000 vertices has depth 10,000. Same V, opposite outcome.

Mechanism. Each recursive call pushes one frame and holds it until its subtree returns, so peak stack equals the height of the DFS tree: at most V−1, usually far less. Python's default limit is 1000 frames (sys.getrecursionlimit()); Java throws StackOverflowError when the thread stack (sized by -Xss, platform-dependent default) is exhausted; C++ has no check and segfaults.

Python
import sys
sys.getrecursionlimit()          # 1000

def dfs(u, adj, seen):
    seen.add(u)
    for v in adj[u]:
        if v not in seen:
            dfs(v, adj, seen)

n = 10_000
adj = {i: [i + 1] for i in range(n - 1)}
adj[n - 1] = []
dfs(0, adj, set())               # RecursionError: maximum recursion depth exceeded

Trace: dfs(0) calls dfs(1) calls dfs(2) … Each nested call consumes one frame and none returns until the chain ends. CPython counts every frame including the module-level ones, so the RecursionError fires just under 1000 nested calls: around vertex 997, not vertex 10,000.

The iterative form has no such ceiling:

Python
def dfs_iter(src, adj):
    seen, stack = {src}, [src]
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

On the same chain the explicit stack never holds more than one element; on a star it holds V−1. Either way it lives on the heap, bounded by memory rather than by a frame limit.

Where it is irrelevant.

ShapeVDFS-tree heightRecursive DFS
Star10,0001fine
Balanced binary tree10,000~14fine
Chain10,00010,000RecursionError
100×100 grid10,000up to 10,000 (snake path)can overflow

Any graph whose DFS height is bounded by a small constant (balanced trees, stars, shallow DAGs, anything you cap with iterative deepening) never touches the limit. So does any iterative implementation. And for complexity analysis the depth is irrelevant in both directions: time is O(V+E) whether you recurse or not, and depth changes only the space constant. Languages with guaranteed tail-call elimination (Scheme, some MLs) can recurse on a chain indefinitely; Python, Java, C++, Go and Rust do not, so the limit applies.

Failure modes. Python raises a catchable RecursionError; raising the limit with sys.setrecursionlimit does not fix the problem, it converts a clean exception into a C-stack segfault that kills the process. Java's StackOverflowError is catchable but leaves you mid-search with a partially built seen set. C++ segfaults with no diagnostic.

Detection is cheap: run the algorithm in CI on a path graph at the maximum expected size, and keep a depth counter that logs the observed maximum. A grid is the trap: it looks shallow but admits a snake path of length V, so it overflows on adversarial input while passing on random input.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach cycle detection in directed graphs to an engineer who has only seen it as a rule of thumb.

Answer

The rule of thumb is right but underspecified: a cycle exists exactly when DFS reaches a vertex that is still on the current recursion stack. The part the slogan drops is still on the stack: an edge to a vertex you have already finished exploring is a cross edge, and treating it as a cycle is the classic false positive.

Mechanism: mark each vertex WHITE (unvisited), GREY (on the stack), BLACK (finished). A GREY neighbour is a back edge → cycle. A BLACK neighbour is a cross edge → ignore. A WHITE neighbour → recurse.

Python
WHITE, GREY, BLACK = 0, 1, 2

def has_cycle(adj):
    colour = [WHITE] * len(adj)
    def visit(u):
        colour[u] = GREY
        for v in adj[u]:
            if colour[v] == GREY:
                return True          # back edge
            if colour[v] == WHITE and visit(v):
                return True
        colour[u] = BLACK
        return False
    return any(colour[u] == WHITE and visit(u) for u in range(len(adj)))

The outer loop matters: a graph can have several components, and starting only at vertex 0 misses cycles elsewhere.

Trace on the diamond A→B, A→C, B→D, C→D (acyclic):

  • visit(A): GREY. →B is WHITE, visit(B): GREY. →D is WHITE, visit(D): GREY, no out-edges, BLACK, returns False. B→BLACK, False.
  • back in A: →C is WHITE, visit(C): GREY. →D is BLACK, not GREY, so skip. C→BLACK, False. A→BLACK, False.

No cycle reported. Now add C→A: visit(C) sees A still GREY → True. That single edge is the whole difference.

Complexity: O(V+E) time, O(V) space for colours plus O(V) recursion depth in the worst case (a path graph). Python's default recursion limit is 1000, so a chain of ~1000 vertices raises RecursionError: convert to an explicit stack, or use Kahn's.

Kahn's algorithm is the credible alternative: compute in-degrees, repeatedly remove a zero-in-degree vertex, decrement its neighbours. If you remove fewer than V vertices, the remainder is exactly the set of vertices on or reachable into cycles.

DFS colouringKahn's
TimeO(V+E)O(V+E)
RecursionO(V) depth, can overflownone, iterative
Extra outputcycle yes/notopological order, cycle members
Stops atfirst back edgeend of queue

When DFS is the wrong tool: you need a topological order anyway (Kahn's gives it free), you need to know which vertices are in cycles (Kahn's leaves them with in-degree > 0), or the graph is deep enough to blow the stack. Tarjan's SCC is the tool when you need every cycle, not just existence: also O(V+E).

Failure modes to name:

  • Single visited set: reports a cycle on any diamond (two paths to one vertex). Detected by testing on A→B, A→C, B→D, C→D.
  • Recursion depth: RecursionError on long chains; detected by a path graph of 10k vertices.
  • Self-loop u→u: caught, because colour[u] is set GREY before the loop runs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you detect a cycle in an undirected graph, and why does the standard directed-graph method fail here?

Answer

Start with the assumption that matters: this is an undirected graph, possibly a multigraph. Self-loops and parallel edges allowed. A cycle exists exactly when a depth-first search finds an edge (u, v) where v has already been visited and v is not the vertex we arrived from. The graph has a cycle if some connected component does, so every vertex has to be tried as a root.

Why the directed code fails: the three-colour DFS from the directed case treats an edge to a vertex still in progress as a back edge. Undirected adjacency lists store each edge twice, so the moment we descend u -> v, v scans its neighbours, finds u still GREY, and returns true. On a two-vertex tree, adj = [[1], [0]], that fires on the very first edge. The directed rule is not wrong; its invariant, an edge to an in-progress vertex closes a directed path back to it, does not survive edges being walkable in both directions. So we exempt the edge we came in on, exactly once.

Python
# Python 3.12
def has_cycle_undirected(n, adj):
    colour = [0] * n  # 0 unseen, 1 in progress, 2 finished

    def dfs(u, parent):
        colour[u] = 1
        seen_parent_edge = False
        for v in adj[u]:
            if v == parent and not seen_parent_edge:
                seen_parent_edge = True          # the tree edge u-v itself
                continue
            if colour[v] == 1:                   # visited and not the parent
                return True
            if colour[v] == 0 and dfs(v, u):
                return True
        colour[u] = 2
        return False

    return any(colour[s] == 0 and dfs(s, -1) for s in range(n))

The edge cases fall out of that one flag:

inputverdictwhy
tree edge u-vno cyclethe parent copy is skipped once
two parallel edges u-vcyclethe second copy finds u in progress
self-loop u-ucycleu is in progress and is not its own parent
cycle in a later componentcycleevery vertex is tried as a root

Skipping every occurrence of the parent instead of one copy hides the parallel-edge case. Dropping the outer any(...) hides a cycle in whichever component is not visited first.

Union-find is the other standard answer and it needs no parent bookkeeping:

Python
# Python 3.12
def has_cycle_union_find(n, edges):
    parent, rank = list(range(n)), [0] * n
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]   # path halving
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return True      # self-loops and parallel edges land here too
        if rank[ru] < rank[rv]:
            ru, rv = rv, ru
        parent[rv] = ru
        if rank[ru] == rank[rv]:
            rank[ru] += 1
    return False

That is O(V + E·alpha(V)) with union by rank and path compression, against O(V + E) for DFS, and it consumes an edge stream without building adjacency lists at all. Two limits: it reports only a boolean, so if the caller wants the cycle's vertices you keep the DFS (or carry a parent map through the union-find forest); and it is meaningless on directed input. The diamond A->B, A->C, B->D, C->D merges into one component and the last edge claims a cycle in a graph that is acyclic.

What I ship depends on input shape and output. Edge list arriving as a stream with a yes/no answer: union-find. Adjacency list already in memory, or the cycle itself must be named: DFS with parent tracking, written iteratively with an explicit stack if the graph can be chain-shaped, so component count is not also a recursion-depth risk.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How does Kahn's algorithm detect cycles during topological sorting, and how does its practical behavior differ from depth-first search (DFS) cycle detection in directed graphs?

Answer

Kahn's algorithm detects cycles through an in-degree peel: every vertex that belongs to a directed cycle, or that lies downstream of a directed cycle, will never have its in-degree reach zero. If the number of vertices dequeued and placed into the topological ordering is strictly less than $|V|$, a cycle exists.

The Mechanism

  1. Compute the in-degree of every vertex in $O(V + E)$ time.
  2. Enqueue all vertices with $\text{in-degree} = 0$.
  3. While the queue is non-empty, pop $u$, append $u$ to the order, and decrement the in-degree of each outgoing neighbor $v \in \text{adj}[u]$. If $v$'s in-degree drops to $0$, enqueue $v$.
  4. Cycle invariant: In any directed cycle, every participating vertex retains at least one internal incoming edge from another cycle member. None can ever reach in-degree zero. Therefore, len(order) < len(V) is necessary and sufficient to declare a cycle.
Python
from collections import deque

def kahn_topological_sort(n: int, adj: list[list[int]]) -> tuple[list[int], bool]:
    in_degree = [0] * n
    for u in range(n):
        for v in adj[u]:
            in_degree[v] += 1

    # Seed with all source nodes
    q = deque([u for u in range(n) if in_degree[u] == 0])
    order = []

    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            in_degree[v] -= 1
            if in_degree[v] == 0:
                q.append(v)

    has_cycle = len(order) != n
    return order, has_cycle

Kahn's vs. DFS Cycle Detection

PropertyKahn's Algorithm (BFS-based)Three-Colour DFS
MechanismIn-degree zero elimination queue.Traversal back-edge to active recursion stack (GREY).
Cycle IsolationIsolates the subgraph of culprits: every vertex left with in_degree > 0 is inside a cycle or reachable from one.Pinpoints the exact cycle path immediately upon hitting a GREY node by unwinding the call stack.
Early TerminationProcesses all upstream acyclic nodes first; only detects the cycle after the queue empties.Can terminate on step 1 if the search root immediately hits an edge closing a cycle ($O(1)$ best-case detection).
Memory & Stack LimitsIterative, queue-driven: $O(V)$ heap memory. Immune to call stack limits.Recursive call depth equals longest path: hits Python's default sys.setrecursionlimit(1000) on deep DAGs unless written iteratively.

Operational Trade-Offs

Use Kahn's when you must emit a topologically sorted execution plan (like a task orchestrator) or identify all broken components simultaneously: the remaining vertices with in_degree > 0 contain all cyclic subgraphs and blocked dependencies. Use three-colour DFS when you require fast-fail aborts or need to log the exact sequence of edges that formed the cycle (A -> B -> C -> A) to an error report.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Given a DAG, how do you tell whether its topological order is unique, and why is counting all valid orders a different class of problem?

Answer

Assume a finite DAG in adjacency-list form, V vertices and E edges, parallel edges allowed, no self-loops.

Direct answer. A DAG has exactly one topological order when the order is forced at every step of Kahn's algorithm: after each removal, exactly one vertex has zero remaining in-degree. If two vertices are ready at the same moment, neither is reachable from the other, so swapping them yields a second valid order. Uniqueness is therefore an O(V+E) question. Counting orders is not.

Mechanically, Kahn's maintains in-degrees and a ready set, and the test is len(ready) > 1 evaluated after every emission, not once at the start.

Python
def unique_topo_order(adj):
    indeg = {u: 0 for u in adj}
    for u in adj:
        for v in adj[u]:
            indeg[v] += 1
    ready = [u for u in adj if indeg[u] == 0]
    order = []
    while ready:
        if len(ready) > 1:
            return None                    # a choice here => at least two orders
        u = ready.pop()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                ready.append(v)
    return order if len(order) == len(adj) else None   # partial output => cycle

Trace on the diamond a->b, a->c, b->d, c->d: ready {a}, emit a; ready {b, c}, stop. The two orders are a,b,c,d and a,c,b,d. Note the input graph has a single source, so "how many sources does this graph have" is not the test. Add the edge b->c and the ready set at step 2 becomes {b}; the count drops to one.

DFS gets there a different way: reverse postorder yields an order but never tells you it is the only one. The equivalent check runs on the produced order v1..vn: unique iff every consecutive pair vi, vi+1 is joined by an edge vi->vi+1, i.e. the DAG has a Hamiltonian path and that path is the order. Verifiable in O(V+E) with a set of edges.

Counting is a different problem. The number of topological orders is the number of linear extensions of the partial order. The standard exact method is a DP over the set of already-emitted vertices:

Python
from functools import lru_cache

def count_topo_orders(adj):
    verts = list(adj); idx = {u: i for i, u in enumerate(verts)}
    pred = [0] * len(verts)
    for u in adj:
        for v in adj[u]:
            pred[idx[v]] |= 1 << idx[u]
    FULL = (1 << len(verts)) - 1

    @lru_cache(maxsize=None)
    def ways(mask):
        if mask == FULL:
            return 1
        return sum(ways(mask | 1 << i) for i in range(len(verts))
                   if not (mask >> i) & 1 and pred[i] & ~mask == 0)
    return ways(0)
TaskCost
exists / cycle evidenceO(V+E)
unique?O(V+E)
one canonical order (heap tie-break, heapq)O((V+E) log V)
exact countO(2^V * V) time, O(2^V) space
enumerate all ordersup to V! outputs

Counting linear extensions is #P-complete, so the exponential DP is not an implementation accident. V=20 is about 10^6 DP states and comfortable; V=25 is 3.3*10^7 states and you are rewriting in a tighter representation or abandoning exactness. Past that, sample instead of count. Enumeration is worse still: it is output-bound, so only ever ask for the first k orders with pruning, never all of them.

The failure this invites is specific: checking readiness only at the first step, or counting the sources of the input graph and declaring the order unique, misses non-uniqueness that appears later. The diamond above has one source and two orders. It survives casual testing because the happy path hides it: the branching tends to appear several removals deep, in exactly the graph a quick check does not exercise.

In practice, run Kahn's with the readiness check at every step. It answers uniqueness and hands you cycle evidence in O(V+E) (vertices left over when the ready set empties). Only reach for the 2^V counter when the question is literally "how many", V is small enough to bound, and you have said what happens when the input turns out to contain a cycle: ways(0) returns 0 there, which is correct but indistinguishable from a bug unless acyclicity is checked first.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does connected components change if the workload grows by two orders of magnitude?

Answer

Assume an undirected graph, 64-bit vertex IDs, and a jump from 1M vertices / 10M edges to 100M vertices / 1B edges. The asymptotic bound O(V+E) does not change. What changes is the constant: memory footprint, recursion depth, and the cost of a distributed round.

At 1M/10M, a single-machine BFS or DFS in memory is fine. At 100M/1B, the same algorithm can still run on one 16GB machine if you use compact types. A CSR adjacency list with 32-bit vertex IDs needs (V+1)4 = 400MB for offsets and E4 = 4GB for edges. A visited bitmap is V/8 = 12.5MB. A BFS queue worst-case holds V vertices: 100M * 4 = 400MB. Total ~4.8GB. If you use 64-bit IDs or Python ints, it does not fit: a Python list of 1B ints is 1B * 28 bytes = 28GB for edges alone.

The first failure mode is recursion. Python's default recursion limit is 1000. A C++ stack is roughly 8MB; with a 48-byte frame that is about 170k frames. A 100M-node path overflows either. Use iterative BFS with an explicit queue.

Union-find is the memory-efficient alternative. A parent array of 100M int32 is 400MB; a rank array of 100M int8 is 100MB. Process edges streaming from disk. No adjacency list is needed. With path compression and union by rank, each edge is near O(1). At 10M edges/sec in C++, 1B edges is ~100s; reading 4GB from disk at 500MB/s adds ~8s. So minutes, not seconds.

Python
from array import array
parent = array('i', range(V))  # 400MB, not a Python list
rank = bytearray(V)

def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

for u, v in edges:  # streamed
    ru, rv = find(u), find(v)
    if ru != rv:
        if rank[ru] < rank[rv]:
            ru, rv = rv, ru
        parent[rv] = ru
        if rank[ru] == rank[rv]:
            rank[ru] += 1

Distributed label propagation is the trap. Each vertex starts with its own ID and repeatedly sends the minimum to neighbors. On a path graph of 100M vertices, the diameter is 100M, so it takes 100M rounds. Each round shuffles 1B edges. That is 10^17 messages, which is not feasible. Detect this by measuring iterations; if they exceed ~100, switch algorithms. A distributed union-find followed by pointer jumping takes O(log V) rounds: log2(100M) ~ 27 rounds.

ApproachMemoryRounds / timeWhen to use
Single-machine BFS/DFS~4.8GBseconds to minutesV<=100M, E<=1B, 32-bit IDs
Union-find streaming~500MBminutesEdges on disk, memory tight
Distributed label propagationcluster RAMO(diameter) roundsLow-diameter graphs
Distributed union-find + pointer jumpingcluster RAMO(log V) roundsHigh-diameter, large scale

The decision turns on memory and diameter. At 1M/10M, BFS in memory. At 100M/1B, use compact types and iterative traversal; if memory is tight, union-find streaming; if distributed, avoid label propagation on high-diameter graphs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Explain the time complexity of Disjoint Set Union with both path compression and union by rank, and describe a scenario where path compression alone is insufficient.

Answer

Direct answer. With both path compression and union by rank, a sequence of $m$ operations on $n$ elements runs in $O(m \cdot \alpha(n))$ amortized, where $\alpha$ is the inverse Ackermann function. $\alpha(n) \le 4$ for every $n$ below $2^{65536}$ (about $10^{19728}$), so the amortized cost per operation is constant for any input that fits in memory.

Path compression alone, with arbitrary linking, is $\Theta(m \log n)$ amortized in the worst case (the tight bound is $\Theta(m \log_{1+m/n} n)$ (Tarjan, 1975)) and a single find can cost $\Theta(n)$. The gap is structural: path compression is reactive, flattening only the path a find actually walks. Union by rank is proactive, capping tree height at $\lfloor \log_2 n \rfloor$ before any find runs.

Why rank bounds height. A root's rank is an upper bound on its subtree height. Two trees of equal rank $r$ merge into one of rank $r+1$, and a tree of rank $r$ holds at least $2^r$ nodes (induction on the merge rule). So rank $\le \log_2 n$ and height $\le \lfloor \log_2 n \rfloor$. Compression never raises rank, so the bound holds for the life of the structure. Union by size (attach the smaller tree under the larger) gives the same guarantee.

Implementation.

Python
class DisjointSet:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, i: int) -> int:
        if self.parent[i] != i:
            self.parent[i] = self.find(self.parent[i])   # path compression
        return self.parent[i]

    def union(self, i: int, j: int) -> bool:
        ri, rj = self.find(i), self.find(j)
        if ri == rj:
            return False
        if self.rank[ri] < self.rank[rj]:
            ri, rj = rj, ri
        self.parent[rj] = ri                             # shorter under taller
        if self.rank[ri] == self.rank[rj]:
            self.rank[ri] += 1
        return True

Scenario where path compression alone is insufficient. Use naive linking (parent[find(u)] = find(v), no rank) and feed it adjacent pairs in order. With $n = 8$, nodes $0..7$:

  • union(0,1): find(0)=0, find(1)=1 → parent[0]=1.
  • union(1,2): find(1)=1, find(2)=2 → parent[1]=2.
  • … union(6,7): parent[6]=7.

Result: 0→1→2→3→4→5→6→7, depth 7. Every union is $O(1)$, find is called on the current root (depth 0) and the new singleton (depth 0), so building the chain costs $\Theta(n)$. Then find(0) walks all 7 edges: $\Theta(n)$ for one operation. Under union by rank the same eight unions all attach to node 0 (rank 1 versus rank 0), depth stays 1, and find(0) is $O(1)$.

Amortized, the adversary does better than one expensive find. Tarjan's bound says path compression alone is $\Theta(m \log n)$ for $m = \Theta(n)$ operations: the adversary controls the union order, so the tree stays deep enough that finds repeatedly walk $\Theta(\log n)$ nodes, and compression only pays back paths already walked. Union by rank removes that lever: height is capped at $\lfloor \log_2 n \rfloor$ regardless of merge order, and compression then drives the amortized cost down to $\alpha(n)$.

OptimizationsAmortized ($m$ ops, $n$ nodes)Max depth before compression
Neither$O(m \cdot n)$$n$
Path compression only$\Theta(m \log_{1+m/n} n)$$n$
Union by rank only$O(m \log n)$$\lfloor \log_2 n \rfloor$
Both$O(m \cdot \alpha(n))$$\lfloor \log_2 n \rfloor$

Failure modes. A recursive find on a depth-$n$ chain blows Python's default recursion limit (1000 frames) with a RecursionError; with rank, depth is $\lfloor \log_2 n \rfloor$ (19 for $n = 10^6$, 30 for $n = 10^9$) so the stack is never at risk. A single $\Theta(n)$ find on a per-request path also spikes tail latency; rank bounds it at $\log n$. Note that rank is an upper bound, not the true height: compression leaves it stale, which is fine because the merge rule only needs a valid bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Given several source nodes (or cells), find the distance from every node to its nearest source. How do you answer that in one traversal instead of one search per source?

Answer

Assume unit-cost moves: unweighted edges, or 4-neighbour steps on a grid. If edges carry weights this becomes multi-source Dijkstra and I'd say that before touching code; everything below is the unweighted case.

Put every source in the queue with distance 0 and run one ordinary BFS. Nothing else about BFS changes.

Python
from collections import deque

def nearest_source(adj, sources):
    dist = {v: -1 for v in adj}
    dq = deque()
    for s in sources:
        dist[s] = 0
        dq.append(s)
    while dq:
        u = dq.popleft()
        for v in adj[u]:
            if dist[v] == -1:
                dist[v] = dist[u] + 1
                dq.append(v)
    return dist

One traversal is enough because of the layer order. BFS drains every node at distance t before any node at distance t+1, and it does that globally across the whole seed set. So the first time a node is reached, the path that reached it is a shortest path from some source, and every later arrival is no shorter. That first distance is the minimum over all sources. It is also why the visited check belongs at enqueue: defer it to dequeue and a node gets queued once per source that reaches it, which quietly reintroduces per-source work.

Complexity is the argument that lands in a design review. One BFS is O(V + E), or O(R·C) cells on an R×C grid. k separate searches are O(k(V + E)) and you take the elementwise minimum of k distance arrays. On a 1000×1000 grid with 200 sources that is 10^6 cell visits against 2×10^8, plus the memory traffic of writing k full arrays. The multi-source queue never exceeds the frontier, so peak memory is the grid's width, not k arrays.

Canonical shapes it maps onto:

  • 01-matrix / nearest zero: the zeros are the sources; dist is the output.
  • Rotting oranges: every rotten orange is seeded at time 0. The answer is the maximum distance over fresh oranges, or -1 if any fresh orange is still unreachable when the queue empties. Elapsed minutes are a global quantity, which is exactly why the simulation must be one traversal.
  • Walls and gates: gates seed 0; cells still -1 when the queue drains are unreachable and stay INF.

Traps I would probe for:

  • Seeding sources one at a time. It returns the correct numbers, so it survives functional tests, and costs k times the work. Worse on the rotting-oranges shape: written as k independent searches, each one's clock starts when that search starts, and the reported time is wrong rather than slow.
  • Searching in the wrong direction: from every target toward the sources instead of from the sources outward. On an undirected grid the numbers come out identical and the bug hides. On a directed graph (one-way corridors in the walls-and-gates style, or any transition graph whose reverse edges do not exist) you compute distances in the wrong direction and they are simply wrong.
  • Pushing sources without setting dist[s] = 0 or marking them visited: a source is then reached from a neighbour and reports a distance of 2 to itself.

If the caller needs to know which source, carry the source id beside the distance or keep a parent pointer per node. Ties are broken by whichever wavefront arrives first; if the tie-break is meaningful I state the rule explicitly instead of letting queue order decide silently.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Problems like Word Ladder, a sliding puzzle, or minimum moves to reach a target are usually solved as graph search, but the graph is never given to you. How do you model one of these as a state-space graph and keep the search tractable?

Answer

The graph is implicit, so the first decision is what a node is. A state is a complete description of the situation: two states may share a node only if every continuation open from one is open from the other at the same cost. Legal actions become edges, and the graph is generated on demand rather than stored: neighbours(state) yields successors and nothing else exists. For Word Ladder the state is the word and edges join words one letter apart; for a sliding puzzle the state is the tile configuration and edges are the legal slides.

Because each move costs one, BFS over that generated graph returns the minimum number of moves: the queue processes states in nondecreasing distance, so the first time the goal is generated you are at the shallowest depth. The guarantee rests entirely on unit cost: let a move cost 2 and plain BFS is wrong; you want Dijkstra, or 0-1 BFS when there are only two weights.

The skeleton is identical across these problems; only neighbours and the state encoding change.

Python
from collections import deque

def min_moves(start, goal, neighbours):
    dist = {start: 0}                 # visited map and distance, marked at enqueue
    q = deque([start])
    while q:
        s = q.popleft()
        for t in neighbours(s):
            if t in dist:
                continue
            dist[t] = dist[s] + 1
            if t == goal:
                return dist[t]
            q.append(t)
    return -1

Mark visited when you enqueue. Marking on dequeue re-queues the same state from several parents and the frontier grows with the branching factor instead of with the state count. The state must be immutable and hashable (tuple, string, bytes) because it is a dict key: a board as a list of lists raises TypeError, while a 16-byte bytes object for a 15-puzzle costs nothing per expansion. Membership tests inside the generator are set lookups, O(1) average for dict/set in CPython, which is what keeps expansion cheap.

problemstatereachable statessuccessors generated per state
Word Ladder, length 5the worda subset of 26^5 = 11,881,3765 × 25 = 125 candidates, most killed by set lookup
8-puzzlepermutation of 9 tiles9!/2 = 181,440at most 4
15-puzzlepermutation of 16 tiles16!/2 ≈ 1.05 × 10^13at most 4
grid with k keys(cell, key bitmask)R · C · 2^kat most 4

Pruning is what keeps that last column small: generate candidates, reject them with the cheapest test available (bounds, wall, dictionary membership), push only survivors. Enumerating the whole 26^5 space and testing afterwards is a different and far larger graph. The parity note in the 8-puzzle row is the same idea one level up: half the permutations are unreachable, so the reachable set is 9!/2, not 9!.

Complexity follows the reachable set, not the puzzle's nominal size: O(S · b) time for S reachable states and b successors generated per state, O(S) memory for the visited map and queue. That is why 8-puzzle BFS is a couple of hundred thousand nodes of routine work and 15-puzzle BFS is infeasible at ~10^13: the model is right and the search strategy has to change to A* or IDA*.

The trap is the grain of the state. Too coarse (it forgets keys held, fuel left, whose turn it is) and the visited set merges genuinely different situations, so BFS reports a distance that is too small and small inputs still pass. Too fine, it carries the path or the move count, and nothing is ever revisited, deduplication stops working, and the search explodes. Take the smallest state that captures everything affecting future legality, and rebuild the path afterwards from a parent map rather than storing it inside the state.

In practice: write the state encoder and neighbours first, then check the search against a case you can count by hand. With words = {"cot", "cog", "dog"}, start "cat", goal "dog", the trace is cat(0) → cot(1) → cog(2) → dog(3). Only then tune representation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does grids as implicit graphs force that a junior answer usually skips?

Answer

The trade-off: an implicit grid graph buys O(V) memory by refusing to store its edges, and pays for that with recomputation on every expansion plus the loss of any per-edge data. The edges are not free: you rebuild them each time you touch a vertex.

Mechanically, neighbours come from offset arithmetic plus a bounds check and an obstacle lookup, run per neighbour per expansion. An explicit adjacency list replaces that with a pointer chase into a prebuilt list. So implicit is cheaper in space and more expensive in time, and the time cost scales with how many times you expand a vertex, not with the size of the grid.

Concretely, a 1,000 x 1,000 grid has 1,000,000 vertices and ~4,000,000 directed edges (2,000,000 undirected):

implicitexplicit adjacency list
memorygrid as bytearray ~1 MB + offset table~200 MB in CPython (1e6 list objects + 4e6 int objects)
neighbour iteration4 adds, 4 bounds checks, 4 grid lookups per expansioniterate a prebuilt list
per-edge datanone; weights need a lookup functionweight, capacity, edge id stored inline
repeated queriesrecompute every timebuild once, reuse

The explicit structure wins when you traverse the same grid many times (build once, amortise the 200 MB), when edges carry data (terrain cost, flow capacity, edge identity for matching or Kruskal) or when the grid is small enough that the memory is irrelevant. Implicit wins when memory is the binding constraint and you expand each vertex roughly once.

Python
MOVES = ((-1, 0), (1, 0), (0, -1), (0, 1))

def neighbours(r, c):
    for dr, dc in MOVES:
        nr, nc = r + dr, c + dc
        if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != "#":
            yield nr, nc

The failure mode is that the recomputation is invisible in a single BFS: each vertex expands once, so the cost is bounded and small. It bites when the same vertex is expanded repeatedly: Dijkstra with a stale-entry priority queue, A* with re-expansion, or 10^4 independent queries on one grid. Detect it by counting expansions and multiplying by per-expansion cost; if expansions are much larger than V, the implicit form is doing redundant work you could have paid for once.

So the decision is: implicit when memory-bound and single-pass, explicit when you traverse repeatedly or need edge attributes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Your search returns the length of the shortest path, but the interviewer wants the path itself. How do you reconstruct it?

Answer

Record the predecessor in the same branch that writes the distance, then walk back from the target. If the parent map and the distance map are written by different code paths, they end up describing different paths.

Mechanically, parent[v] = u is written exactly when dist[v] improves: in BFS that is the moment the node is discovered and enqueued, in Dijkstra the moment nd < dist[v] and the new entry goes on the heap. Never write a parent after the node has been settled, and never on a scan that did not improve dist.

Python
import heapq          # Python 3.12+

def shortest_path(graph, s, t):
    dist = {s: 0.0}
    parent = {s: None}
    pq = [(0.0, s)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:
            continue                       # stale heap entry
        if u == t:
            break                          # t settled; valid for w >= 0
        for v, w in graph[u]:
            nd = d + w
            if nd < dist.get(v, float("inf")):   # strict: ties never move a parent
                dist[v], parent[v] = nd, u
                heapq.heappush(pq, (nd, v))
    if t not in dist:
        return []                          # unreachable: no parent, no path
    path, node = [], t
    while node is not None:
        path.append(node)
        node = parent[node]
    path.reverse()
    assert path[0] == s                    # cheap guard against parent drift
    return path

An unreachable target has no entry in parent and dist[t] is infinite, so return empty or None explicitly; never hand back a chain that stops at some other vertex. The cost of reconstruction is one parent entry per vertex, O(V) extra space, plus an O(L) walk-back for a path of length L. The alternative, carrying the whole path in every heap entry, duplicates up to O(V) per entry and reaches O(V·E) of heap memory in the worst case, which is the bill people are surprised by.

Ties need an explicit policy. With two routes of equal length, an unguarded <= picks by adjacency scan order, which in practice is dict or set iteration order and can change after a refactor. If the API promises deterministic output, tie-break on the parent itself: replace only when nd < dist[v] or nd == dist[v] and u < parent[v] (with the None case for s handled), which keeps the distance and gives a stable chain. With zero-weight cycles there are infinitely many walks of the minimum length, so the tie-break has to be a total order on vertices to keep the answer finite.

The classic bug is a parent write outside the dist-improving branch:

scan into tdist[t]parent[t]walk-backverdict
a→t, w=12at-a-ssums to 2
b→t, w=1, nd == dist[t], parent written anyway2bt-b-ssums to 2, but a different path
c→t, w=1, dist[c]=3, parent written outside the guard2ct-c-ssums to 4

Step 2 is the benign tie: t-b-s is a genuine shortest path. Step 3 is the failure: dist[t] stays 2 while parent[t] points at a node with dist[c] = 3, so the walk-back returns a chain of real edges whose weights sum to 4. The caller gets a "shortest" path that is not the one the distance came from. Make the write fully unguarded and the pointers can form a cycle, so the walk-back never terminates. Both survive casual tests because equal-length collisions are rare and the usual scan order happens to make the last write the correct one.

In practice, walk back with a loop rather than recursion: a 200,000-vertex route is ordinary in a road or dependency graph, and a recursive walk dies at CPython's default recursion limit of 1000 well before memory is a concern. Test on a graph with two equal-length routes and one longer route, and assert both path[0] == s and the edge weights summing to dist[t].

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of dijkstra's algorithm?

Answer

Core answer

I'd refuse Dijkstra when the problem breaks one of its preconditions, or when its cost model doesn't fit the workload. Four grounds come up in practice: negative edge weights, all-pairs results on a dense graph, weights that change between queries, and a graph large enough that a plain implementation misses the latency budget.

Negative edges. Dijkstra finalises a vertex when it pops the minimum tentative distance and never reconsiders it. That is only safe if no later path can be shorter, which requires every edge weight ≥ 0. With one negative edge the answer is silently wrong: no exception, no assertion.

Python
# A->B = 2, A->C = 5, C->B = -4
# Dijkstra from A: dist = {A:0, B:2, C:5}
# pop B (2) -> finalise B
# pop C (5) -> relax C->B: 5 + (-4) = 1, but B is already finalised
# reported dist[B] = 2; true shortest path A->C->B = 1

Bellman-Ford handles negatives in O(V·E) and detects negative cycles; on a DAG, relaxing in topological order is O(V+E) and also handles negatives. Both are slower than Dijkstra's O((V+E) log V) with a binary heap, so I only pay that when the weight domain demands it.

All-pairs on a dense graph. Running Dijkstra from every source costs O(V·(V+E) log V). At V=1000, E≈500k (dense), that is roughly 5×10⁹ operations; Floyd-Warshall is O(V³) = 10⁹. For sparse graphs the reverse holds and Johnson's algorithm (O(V·E + V² log V)) wins.

Dense single-source. Even for one source, a binary-heap Dijkstra on a dense graph is O((V+E) log V) ≈ 5×10⁶ at the sizes above, while the array-scan variant is O(V²) = 10⁶. Refuse the heap version, not Dijkstra.

Dynamic weights. Dijkstra recomputes from scratch. If a routing service takes thousands of weight updates per second, re-running per update is the refusal; incremental algorithms (D* Lite) or recomputation over the affected region are the alternatives.

Scale. A continental road network is on the order of 20M nodes and 50M edges. Plain Dijkstra is seconds per query; contraction hierarchies answer in well under a millisecond after preprocessing that takes minutes to hours. If the query budget is sub-millisecond, plain Dijkstra is the wrong tool.

Unweighted or hop-count. BFS is O(V+E) with no heap; Dijkstra's log factor buys nothing.

NeedAlgorithmCostWhy not Dijkstra
Single source, non-negativeDijkstra (binary heap)O((V+E) log V)—
Single source, negative edgesBellman-FordO(V·E)finalises vertices, never reconsiders
Single source, DAGtopo-order relaxationO(V+E)handles negatives; heap is wasted
All-pairs, denseFloyd-WarshallO(V³)V runs of Dijkstra = O(V³ log V)
All-pairs, sparseJohnson'sO(V·E + V² log V)—
UnweightedBFSO(V+E)heap overhead pointless

When Dijkstra is right: single source, non-negative weights, static graph, sparse-to-moderate density, and you need one source's distances. That is the default and I'd keep it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain the priority queue in Dijkstra without using the usual slogan?

Answer

The 90-second version

The priority queue isn't an optimisation bolted onto Dijkstra; it is the correctness argument. Dijkstra keeps a set S of vertices whose shortest distance is settled, plus a tentative distance for everything else. The invariant is: when the heap hands you the smallest tentative distance d for vertex u, that d is final. No shorter path to u exists.

Why: take any path from the source to u that isn't settled yet. Walk along it until the first vertex y that isn't in S. The vertex just before y, call it x, is settled, so dist[x] is final, and dist[y] ≤ dist[x] + w(x,y), which is at most the length of the path prefix. If the whole path were shorter than d, then dist[y] < d, and y is sitting in the heap with a smaller key than u, so the heap would have handed you y first. It didn't. No shorter path exists.

That argument rests on non-negative weights, not on the heap being clever. The heap's job is narrow: extract the minimum tentative distance in O(log n) instead of scanning every vertex. Remove the heap and the algorithm is still correct, just O(V²).

Lazy deletion vs decrease-key

Relaxing an edge can lower a vertex's tentative distance. Two ways to handle that:

Lazy (push duplicates)Indexed heap with decrease-key
Heap sizeO(E)O(V)
Per relaxationone push, O(log E)one decrease-key
Binary heap totalO(E log V)O((V+E) log V)
Fibonacci heap—O(E + V log V) amortized
Practicalusually wins: no position array, better cache behaviourwins when decrease-key is cheap and the graph is dense

Lazy deletion pushes the improved distance as a new entry and leaves the old one in the heap. On pop, if d > dist[u], the entry is stale: skip it. That check is a performance guard, not a correctness one: a stale pop re-relaxes u's edges with a larger d, and every one of those relaxations fails the nd < dist[v] test, because u already relaxed v with the smaller distance. You waste work; you don't get a wrong answer.

Python
import heapq

def dijkstra(adj, src):
    dist = {src: 0}
    pq = [(0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:          # stale entry, skip
            continue
        for v, w in adj[u]:
            nd = d + w
            if nd < dist.get(v, float("inf")):
                dist[v] = nd
                heapq.heappush(pq, (nd, v))
    return dist

Trace

Graph: A→B 1, A→C 4, B→C 1, B→D 5, C→D 1. Source A.

popddist[u]action
(0,A)00relax B→1, C→4; push (1,B),(4,C)
(1,B)11relax C→2 (was 4), D→6; push (2,C),(6,D)
(2,C)22relax D→3 (was 6); push (3,D)
(3,D)33no outgoing edges
(4,C)42stale, skip
(6,D)63stale, skip

Six heap entries for four vertices; two were stale. Final distances: A 0, B 1, C 2, D 3.

Where it breaks

Negative edges destroy the invariant, not the heap: a path that leaves S later can come back with a smaller total, so the popped minimum is no longer final. That's Bellman-Ford's territory. With non-negative weights the only real failure mode is memory: on a dense graph the lazy heap can hold O(E) entries, which for a million-edge graph is a million tuples. If that matters, switch to an indexed heap and pay the position bookkeeping.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How does the Bellman-Ford algorithm detect negative weight cycles in a directed graph, and why does Dijkstra's algorithm fail when negative edge weights are present?

Answer

Dijkstra's algorithm assumes that edge weights are non-negative. Under this assumption, extracting the unvisited vertex with the minimum tentative distance is a permanent finalization step: adding non-negative edge weights to any other path will never produce a total distance smaller than the current extracted distance.

When negative edge weights exist, this greedy invariant breaks immediately. A vertex already marked finalized can later be reached via an alternate branch with a large negative weight, producing a shorter path after Dijkstra has already closed the vertex and refused to relax its outgoing edges again.

Graph example:
  A -> B (weight = 2)
  A -> C (weight = 5)
  C -> B (weight = -4)

Dijkstra from A:
1. dist[A] = 0, dist[B] = 2, dist[C] = 5
2. Extract B (distance 2), mark B finalized.
3. Extract C (distance 5), relax C -> B: tentative dist = 1.
   If finalized nodes are skipped, B is never updated or reopened;
   if reopened without checks, a negative cycle causes an infinite loop.
True shortest path to B is A -> C -> B with cost 1.

Bellman-Ford does not make greedy finalizations. Instead, it relies on structural induction: in any graph with $V$ vertices containing no negative weight cycles, a simple shortest path visits at most $V$ vertices and contains at most $V - 1$ edges.

Relaxing every edge in the graph guarantees that after $k$ passes, Bellman-Ford has computed the true shortest paths for all paths consisting of at most $k$ edges. Therefore, after $V - 1$ passes, all shortest simple paths are guaranteed to be fully settled.

Python
def bellman_ford(vertices, edges, source):
    dist = {v: float("inf") for v in vertices}
    dist[source] = 0

    # V - 1 passes relax every edge
    for _ in range(len(vertices) - 1):
        for u, v, w in edges:
            if dist[u] != float("inf") and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w

    # V-th pass: any further relaxation proves a reachable negative cycle
    for u, v, w in edges:
        if dist[u] != float("inf") and dist[u] + w < dist[v]:
            raise ValueError("Reachable negative-weight cycle detected")

    return dist

Detection of negative weight cycles follows directly: Bellman-Ford performs a $V$-th relaxation pass over all edges. If any edge u -> v can still be relaxed such that dist[u] + w < dist[v], that path must contain at least $V$ edges, meaning at least one vertex is visited twice. This proves the existence of a reachable cycle whose total sum of edge weights is strictly negative, which would permit distances to decrease toward $-\infty$.

PropertyDijkstraBellman-Ford
Edge Weight ConstraintRequires $w \ge 0$Supports arbitrary weights ($w \in \mathbb{R}$)
Time Complexity$O((V + E) \log V)$ with binary heap$O(V \cdot E)$
Negative Cycle BehaviorSilent corruption or infinite loopDetects via $V$-th edge sweep

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-17

You need single-source shortest paths in a graph where every edge weight is 0 or 1. How do you do better than Dijkstra here, and why does your approach work?

Answer

Assumptions first: one source, exact distances to every vertex (plus parent pointers when the path itself matters), and every edge weight is 0 or 1. Under those, the binary heap is wasted work. A deque gives Dijkstra's greedy guarantee in O(V + E).

Python
from collections import deque

def zero_one_bfs(src, adj):
    dist = {v: float("inf") for v in adj}
    parent = {v: None for v in adj}
    dist[src] = 0
    q = deque([src])
    while q:
        u = q.popleft()
        for v, w in adj[u]:
            nd = dist[u] + w
            if nd < dist[v]:            # the only gate — there is no visited set
                dist[v] = nd
                parent[v] = u
                (q.appendleft if w == 0 else q.append)(v)
    return dist, parent

The invariant that makes it correct. The deque stays sorted by distance, and it never holds more than two distinct values: some d at the front, d+1 at the back. Popping u at distance d can only mint a new entry of value d (a 0-edge, pushed to the front) or d+1 (a 1-edge, pushed to the back), so the ordering survives every pop and push. Extraction is therefore monotone non-decreasing, and with non-negative weights the first time u leaves the deque its distance is final. That is exactly the step Dijkstra buys with a heap and a finalised check: 0-1 BFS is Dijkstra with a two-bucket priority queue.

Why O(V + E): each vertex enters the deque at most twice. Any improvement to dist[v] is strictly smaller, while pop levels never decrease, so a second improvement to v can only come from the same pop level d, and the only values available there are d and d+1. At most 2V pushes, one adjacency scan per pop, no logarithm.

algorithmon this inputwhat it actually computes
plain BFSO(V + E) but wrongfewest edges, ignores cost
0-1 BFSO(V + E)least cost; deque, two layers
Dijkstra, binary heapO((V + E) log V)least cost, any non-negative weights
Bellman-FordO(VE)least cost with negative edges

Concrete figure: 200,000 vertices, 400,000 edges. The heap version does about 600,000 × log2(200,000) ≈ 600,000 × 17.6 ≈ 10.6 million heap operations; the deque version does 600,000 edge scans and at most 400,000 pushes. If every weight were 0 or every weight were 1, plain BFS would already be correct and I would use it.

The trap worth naming: the plain-BFS habit of marking a vertex discovered when it first enters the queue breaks the distance guarantee. Take s → a with weight 1, s → b with weight 0, b → a with weight 0. First discovery of a is via the weight-1 edge, distance 1; the real distance is 0. Marking visited at enqueue returns 1 and never looks again. Relax strictly on nd < dist[v], let a vertex re-enter the deque as often as it improves, and skip nothing at pop.

Where it stops: any weight ≥ 2 breaks the two-layer invariant. The deque can hold values more than one apart and the front is no longer the minimum. For small integer weights 0..W use Dial's bucket queue (O(E + V·W)); otherwise Dijkstra. One weight of −1 is worse: the monotone order fails outright, and if a negative cycle is reachable the cost is unbounded below, so run Bellman-Ford and report the cycle rather than a distance.

Classic shapes that reduce to it: a grid where entering a cell is free or costs one (for example minimum-cost-to-flip-arrows grid, where following an arrow already pointing the right way costs 0 and flipping it costs 1. 22,500 cells × 4 directions ≈ 90,000 states, about 360,000 edges), and any "at most k free moves" problem where a step costs 0 or 1 once the state includes how many moves you have burned.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

When is bidirectional search preferred over unidirectional BFS or Dijkstra, and what exact termination conditions guarantee the shortest path?

Answer

Bidirectional search is preferred when you have a known, fixed pair of source $s$ and target $t$ in a state space with a high uniform branching factor $b$, and transitions in reverse from $t$ are computationally accessible and share a comparable branching factor.

The Complexity Win

In an unweighted graph where the shortest path has distance $d$, standard unidirectional BFS pushes the frontier out to radius $d$, expanding $O(b^d)$ nodes. Bidirectional search expands two frontiers of radius $\approx d/2$, reducing total visited states to $O(b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor})$.

For branching factor $b = 10$ and depth $d = 8$:

  • Unidirectional BFS: $\approx 10^8$ states in memory.
  • Bidirectional BFS: $\approx 2 \times 10^4$ states in memory.

It is not preferred when:

  1. The target is non-specific or multi-node (e.g., "find any node matching predicate $P$").
  2. Reverse edges are missing, asymmetric, or costly to compute (in a directed graph, the reverse frontier requires transpose edges $E^R$).
  3. Graph diameter is tiny, or goal-directed heuristics ($A^*$) prune the space more effectively without the coordination overhead of two frontiers.

Exact Termination Conditions

A common interview bug is stopping as soon as any node is reached from both directions. That does not guarantee a shortest path.

1. Unweighted Graphs (BFS)

If you expand nodes one by one and terminate immediately when a node is seen by both frontiers, you can return a suboptimal path. For example, consider an odd shortest path $s - a - b - t$ of length 3, and a detour path $s - x - y - z - t$ of length 4. If an alternating node-by-node search expands along the detour first, frontiers may collide at a length-4 node before evaluating the length-3 edge $(a, b)$.

To guarantee shortest-path optimality, use one of two invariants:

  • Layer-by-layer expansion with best-seen tracking: Expand an entire depth layer at a time (from the smaller frontier). Track $\mu = \infty$ (the length of the shortest path found so far). When processing layer $k$, if an edge connects to a node already visited in the opposite frontier at distance $r$, record $\mu = \min(\mu, k + 1 + r)$. After finishing the entire layer $k$, if $\mu < \infty$, terminate and return $\mu$.
Python
from collections import deque

def bidirectional_bfs(adj, s, t):
    if s == t: return 0
    q_f, q_b = deque([s]), deque([t])
    dist_f, dist_b = {s: 0}, {t: 0}
    mu = float("inf")

    while q_f and q_b:
        # Expand an entire layer from the smaller frontier
        if len(q_f) <= len(q_b):
            for _ in range(len(q_f)):
                u = q_f.popleft()
                for v in adj[u]:
                    if v not in dist_f:
                        dist_f[v] = dist_f[u] + 1
                        q_f.append(v)
                    if v in dist_b:
                        mu = min(mu, dist_f[u] + 1 + dist_b[v])
        else:
            for _ in range(len(q_b)):
                u = q_b.popleft()
                for v in adj[u]:
                    if v not in dist_b:
                        dist_b[v] = dist_b[u] + 1
                        q_b.append(v)
                    if v in dist_f:
                        mu = min(mu, dist_b[u] + 1 + dist_f[v])

        # Once an entire layer has finished, mu is provably minimal
        if mu != float("inf"):
            return mu

    return -1

2. Weighted Graphs (Dijkstra)

In weighted graphs with non-negative edges, stopping when the first node is popped or enqueued by both searches can fail because shorter paths through unexpanded edges remain in the priority queues.

Condition: Maintain $\mu = \infty$ as the best candidate distance found so far.

  1. When relaxing edge $(u, v, w)$ from the forward search, if $v$ has a known backward distance $\text{dist}_B[v]$, update $\mu = \min(\mu, \text{dist}_F[u] + w + \text{dist}_B[v])$. Apply the symmetric check for backward relaxation.
  2. Let $\text{top}_F$ and $\text{top}_B$ be the minimum keys currently at the top of the forward and backward priority queues.
  3. Terminate if and only if: $$ \text{top}_F + \text{top}_B \ge \mu $$ Any path not yet examined must traverse at least one forward edge leaving settled nodes (cost $\ge \text{top}_F$) and one backward edge entering settled nodes (cost $\ge \text{top}_B$), giving a total length $\ge \text{top}_F + \text{top}_B \ge \mu$. Hence $\mu$ is guaranteed to be optimal.
Python
import heapq

def bidirectional_dijkstra(adj_f, adj_b, s, t):
    if s == t: return 0
    pq_f, pq_b = [(0, s)], [(0, t)]
    dist_f, dist_b = {s: 0}, {t: 0}
    visited_f, visited_b = set(), set()
    mu = float("inf")

    while pq_f and pq_b:
        if pq_f[0][0] + pq_b[0][0] >= mu:
            return mu

        # Advance the search with the smaller top key
        if pq_f[0][0] <= pq_b[0][0]:
            d, u = heapq.heappop(pq_f)
            if u in visited_f: continue
            visited_f.add(u)
            for v, w in adj_f[u]:
                if dist_f.get(v, float("inf")) > d + w:
                    dist_f[v] = d + w
                    heapq.heappush(pq_f, (dist_f[v], v))
                    if v in dist_b:
                        mu = min(mu, dist_f[v] + dist_b[v])
        else:
            d, u = heapq.heappop(pq_b)
            if u in visited_b: continue
            visited_b.add(u)
            for v, w in adj_b[u]:
                if dist_b.get(v, float("inf")) > d + w:
                    dist_b[v] = d + w
                    heapq.heappush(pq_b, (dist_b[v], v))
                    if v in dist_f:
                        mu = min(mu, dist_b[v] + dist_f[v])

    return mu if mu != float("inf") else -1

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does bipartite testing interact with rollback, and where do people ignore that?

Answer

Rollback and bipartite testing meet at one point: the bipartite check is the commit precondition for a two-way cut, and rollback is the bill you pay when you run that check in the wrong scope.

Take a shard split, a blue/green cutover, or a tenant re-assignment. You are proposing a two-way partition of a dependency graph with no edge left inside a side, which is exactly bipartiteness. Pass the check, commit the split. Fail it after writes have landed, roll back. The interaction is a scope mismatch: bipartiteness is a whole-graph invariant, while the migration and its rollback are per-row operations.

The mechanism, and where the two diverge

Two-colouring decides it. Assign each vertex a side; every edge must join different sides; an edge whose ends are already on the same side proves an odd cycle and the graph is not bipartite. Nothing else in the check matters, and no partitioning heuristic or approximation substitutes for it.

The mismatch: a traversal that colours one component proves only that component. If you validate the tenants you are about to move, or the first connected region you happen to hit, a violation sitting in an untouched component survives validation and appears after commit.

Python
colour = {}
for s in vertices:                  # not "s = 0"
    if s in colour: continue
    colour[s] = 0; q = deque([s])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in colour: colour[v] = 1 - colour[u]; q.append(v)
            elif colour[v] == colour[u]: return False, (u, v)
return True, None

Trace it on adj = {a:[b], b:[a,c], c:[b], x:[y,z], y:[x,z], z:[x,y]}. From a: a=0, b=1, c=0, queue drains, and that component is bipartite. A version that stops there returns True. The loop over vertices continues: x=0, then y and z both receive 1 from x; popping y finds z already coloured 1, equal to y's colour, and returns False with the edge (y,z). One for line is the difference between "clean" and "here is the offending edge".

Where rollback turns a bad check into a bad day

Hypothetical figures, but shaped like real splits: 10,000 tenants, 4,100 moved in the first 25 minutes with per-tenant validation passing, and 3 intra-side edges that only the global scan sees. Rollback deletes those 4,100 rows from the new shard and re-inserts them elsewhere. The graph afterwards is not the graph you validated: sequence values on the new shard advanced and those ids are burned, audit rows written under the new topology stay, denormalized copies of the old assignment are stale. Re-running the check after rollback can fail on edges that did not exist before the migration started, which is a rollback of a rollback.

Alternatives and the criteria that decide

ApproachCostUse whenFails when
Full two-colour scanO(V+E), needs the graph addressablegraph fits in memory or streams off a tableedges appear mid-migration
Parity union-find, union by sizenear-constant per edgeedges arrive continuously and you want the conflict at insert timeedges are removed; plain DSU has no undo
Parity DSU with an undo stacksame, plus memory for the stackremovals are LIFO, which is what rollback isrollback happens out of order; rebuild instead

Forward-fix is the fourth option and often the cheaper one: move the vertex that owns the violating edge to the other side and re-check only that vertex's edges. It beats undoing 4,100 rows when the offending vertex has few edges, and loses when its degree is high, because each moved neighbour can create a new conflict.

Whichever you pick, return the conflicting edge rather than a boolean. The (u, v) pair is what the runbook and the post-incident review need, and it is the one thing a boolean check throws away.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What causes frontier and state memory exhaustion in large graph traversals, and how do iterative deepening and external-memory techniques mitigate it?

Answer

In large-scale graph traversal like Breadth-First Search (BFS) or Dijkstra's algorithm, memory exhaustion stems from two distinct structures: the frontier queue (nodes discovered but not yet expanded) and the visited state table (nodes retained to prevent cycle re-expansion).

The Mechanism of Exhaustion

For a graph with effective branching factor $b$ and search depth $d$, BFS frontier size scales as $O(b^d)$, which represents the width of the graph level. The visited set consumes $O(V)$ space. In state-space graphs (e.g., puzzles, model checkers, pathfinding grids), $V$ can easily exceed $10^9$ states. At 16–32 bytes per node pointer and hash table entry, keeping 100 million states in memory demands several gigabytes; at 1 billion states, RAM is completely saturated.

Mitigation 1: Iterative Deepening (IDDFS / IDA*)

Iterative Deepening Depth-First Search replaces the $O(b^d)$ queue of BFS with depth-bounded DFS passes: $d = 0, 1, 2, \dots$.

  • Space: Drops from $O(b^d)$ to $O(d)$ stack frames. For depth 30 with $b=10$, standard BFS needs $10^{30}$ queue entries; IDDFS needs only 30 stack frames.
  • Recomputation overhead: Nodes at depth $k$ are re-expanded $d - k + 1$ times. The total expansions sum to $\sum_{k=0}^d (d - k + 1) b^k = O(b^d)$. When $b \ge 2$, the ratio of IDDFS node visits to BFS visits is $\frac{b}{b-1}$. For $b=10$, the recomputation overhead is only $\approx 11%$.
  • The Catch: In a general graph with cycles (unlike a tree), DFS can explore exponentially many duplicate paths unless it tracks visited states. If a global visited set is kept, space reverts to $O(V)$. Thus, IDDFS works best on trees, DAGs with low path multiplicity, or with compact local cycle checking along the current recursion branch.
Python
# Iterative Deepening Search (bounded recursion depth, O(d) memory)
def iddfs(adj, source, target, max_depth):
    for limit in range(max_depth + 1):
        visited_path = set()  # Only tracks nodes on current call stack: O(d) space
        found = _dls(adj, source, target, limit, visited_path)
        if found is not None:
            return found
    return None

def _dls(adj, u, target, limit, path):
    if u == target:
        return [u]
    if limit <= 0:
        return None
    path.add(u)
    for v in adj.get(u, []):
        if v not in path:  # Prevents cycling along the active branch
            res = _dls(adj, v, target, limit - 1, path)
            if res is not None:
                return [u] + res
    path.remove(u)  # Backtrack: frees memory
    return None

Mitigation 2: External-Memory Graph Traversal

When graphs cannot fit in RAM and state deduplication cannot be dropped, external-memory search (e.g., Munagala-Ranade BFS) offloads the frontier and visited sets to sequential disk storage.

TechniqueSpace ComplexityLatency / I/O Trade-offBest Applied When
Standard BFS$O(b^d)$ RAMMinimal runtime overhead until swapping/OOM crashes process.Frontier and visited set fit cleanly in RAM.
IDDFS$O(d)$ RAM$\approx \frac{b}{b-1}$ node expansions; high overhead if dense graph has many cycles.High branching factor, tree-like state space, deep solutions where memory is the bottleneck.
External BFS (Sort-and-Merge)$O(1)$ RAM, $O(V + E)$ diskReplaces random RAM lookups with sequential sorting passes over disk blocks; high I/O latency.Massive general graphs with cycles that exceed physical RAM but require exact BFS levels.

In external BFS, the frontier at level $d$ is written sequentially to disk. Neighbor expansion generates an unsorted list of candidate vertices. Duplicate candidates and vertices already present in level $d$ or $d-1$ are eliminated using external merge-sort rather than random hash table lookups, eliminating random I/O bottlenecks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document choosing the algorithm so the next owner can operate it?

Answer

The choice lives in three artifacts, each answering a different question the next owner will ask. Why this algorithm goes in an ADR committed next to the code. What breaks it goes in the runbook. What must stay true goes in an assertion at the call site. A decision recorded only in a PR description or a Slack thread is not documentation: the next owner will not find it, and six months later neither will you.

MARKDOWN
# ADR-014: Shortest-path algorithm for the routing service

Status: accepted, 2024-03-11

Context: edge weights are travel times in seconds, emitted by the
  traffic model. Non-negative by construction.

Decision: Dijkstra with a binary heap (networkx 3.3 dijkstra_path).

Alternatives rejected:
  - BFS: ignores weights, returns fewest-hops, not fastest.
  - Bellman-Ford: O(V*E) = 10^13 relaxations on the current graph.

Assumption that makes this valid: no negative edge weights.
  If the traffic model emits a negative delta, this is wrong.

Consequences: p99 route query 180 ms at V=1M, E=10M.
  Measured 2024-03-08, bench/route_bench.py.

The assumption line is the load-bearing one. "Dijkstra" alone tells the next owner nothing about when to distrust it; "Dijkstra because weights are non-negative, and here is what happens if they are not" tells them exactly which change to the traffic model invalidates the choice.

ArtifactAnswersLives
ADRwhy this algorithm, what was rejecteddocs/adr/014-routing-algorithm.md
Runbookwhat to watch, what to do when it breaksrunbooks/routing.md
Assertion + commentthe invariant the code depends oncall site

The runbook carries the operational half: an alert on negative_weight_count > 0 at ingest, a nightly bench that fails if p99 exceeds 400 ms, and the fallback. Swap to Bellman-Ford, which costs roughly 10^13 relaxations on the current graph, so it is a degraded-mode answer, not a drop-in. Naming the fallback and its cost is what lets someone on call make the call at 3 a.m. without paging you.

Why the numbers matter to the record: on a hypothetical graph of V=1M, E=10M, BFS does 11M edge relaxations, Dijkstra does about (V+E)·log V ≈ 220M heap comparisons, and Bellman-Ford does V·E = 10^13. Without those figures the ADR cannot distinguish "we chose the cheap one" from "we chose the only feasible one," and the next owner cannot tell whether a 2× graph growth is survivable.

Three ways this documentation rots. The assumption is stated but nothing enforces it: fix with an assertion at ingest and a test that feeds a negative weight and expects a failure. The benchmark is undated and unnamed: a number without a date and a script is folklore. The input distribution is missing: "p99 180 ms" means nothing without the graph shape it was measured on, so record V, E, and the degree distribution alongside it.

The test of the record: the next owner can tell, without asking you, which assumption would invalidate the choice, how they would detect that it broke, and what they would do instead.

Curated: · Written: · Reviewed:

Difficulty: Medium