Graphs and Graph Algorithms Questions
Graph representations (adjacency list and adjacency matrix) and the traversal algorithms applied to general, non-tree structures: BFS, DFS, topological sort (Kahn's algorithm and DFS-based), shortest paths (Dijkstra, Bellman-Ford, A*), minimum spanning trees, cycle detection, connected components, and union-find. Covers modeling a problem as a graph even when the underlying data is not obviously graph-shaped, such as state-space search, an implicit graph over strings or grid cells (for example Word Ladder), or a task-dependency graph, and implementing these traversals with a hash map or hash set as the storage vehicle (adjacency map, visited set, memoization table), not the subject being tested. The graded skill is traversal, ordering, connectivity, or shortest-path reasoning over nodes and edges. This topic does not own: traversal, reconstruction, or serialization of a single-rooted binary tree (preorder, inorder, postorder, or level-order implementation, rebuilding a tree from traversal arrays, lowest common ancestor, binary search tree validation), which belongs to binary trees and binary search trees even though a tree is technically a graph; hash table internals such as hash function design, collision resolution, and load factor and resizing, which belong to hashing and hash tables; and deriving or comparing algorithmic complexity across graph algorithms without implementing them, such as comparing the time complexity of BFS, DFS, Dijkstra, and A*, which belongs to time and space complexity analysis. One of the highest-signal areas in senior coding interviews.
Prove why the Bellman-Ford algorithm detects negative cycles reachable from the source: show why V-1 relaxations suffice for shortest path correctness and why an extra pass exposes negative cycles. Analyze its worst-case time complexity. Then propose practical approaches to scale negative-cycle detection for massive graphs with limited memory (sampling, partitioned checks, heuristics).
Sample Answer
Direct answer
V−1 relaxation passes suffice because the longest a SIMPLE (non-vertex-repeating) shortest path can be, on a graph with V vertices, is V−1 edges, and each full pass is guaranteed to extend at least one more edge of every such optimal path's correct distance. A V-th pass that still finds an improvement is therefore evidence of something a simple path could never produce: a path effectively "longer" than V−1 edges is only possible if it revisits a vertex, and revisiting only helps if the revisited loop is net-negative, which is precisely a negative cycle. Worst-case time is O(V⋅E). At massive scale, exact detection remains O(VE) in the worst case, but its practical cost can be reduced with sampling, source partitioning, and early-termination heuristics that trade some detection latency (not correctness, when applied carefully) for far less work on graphs that are usually cycle-free.
Structured elaboration
Proof that V−1 passes suffice. Let P=(s=p0,p1,…,pk=t) be a shortest path from s to t with the fewest possible edges among all shortest paths (a simple shortest path; if the graph has no negative cycle reachable from s, every shortest path has an equivalent simple representation, since removing any cycle from a path can only decrease or preserve its weight when the cycle is non-negative, and cannot be forced by a negative cycle if none is reachable). Claim: after pass i of relaxation, dist[pi] equals δ(s,pi), the true shortest distance.
Proof by induction on i. Base case i=0: dist[p0]=dist[s]=0=δ(s,s) from initialization, before any pass runs.
Inductive step: assume dist[pi−1]=δ(s,pi−1) holds after pass i−1. Pass i relaxes every edge of the graph, in particular the edge (pi−1,pi) (since edges are relaxed regardless of order within a pass, every edge gets its chance during every pass). Relaxing that edge sets dist[pi]≤dist[pi−1]+w(pi−1,pi)=δ(s,pi−1)+w(pi−1,pi)=δ(s,pi), using that P is a shortest path, so its prefix to pi is also shortest (a standard property of shortest paths: sub-paths of shortest paths are themselves shortest). Since dist can never fall below the true distance (relaxation only ever assigns achievable path costs), dist[pi]=δ(s,pi) after pass i, completing the induction.
Since P has k≤V−1 edges, dist[t]=dist[pk]=δ(s,t) is guaranteed correct after at most V−1 passes, for every t simultaneously (the same argument applies to every vertex's own shortest simple path independently).
Proof that an extra pass exposes a negative cycle. If no negative cycle is reachable from s, every vertex's shortest distance is achieved by SOME simple path (of length ≤V−1), by the argument above, so a V-th pass finds nothing left to improve: every dist value is already correct and stable. Conversely, if a negative cycle C is reachable from s, then for any vertex t on C, one can construct paths from s to t of arbitrarily low cost by looping C additional times before finally reaching t (each loop subtracts ∣w(C)∣>0 from the total). No finite value of dist[t] can be a true shortest distance (there is no minimum; the infimum is −∞), so relaxation along C's edges can never stabilize: some edge on or reachable-from C will always still offer an improvement on the V-th pass (and every pass thereafter), which is exactly the extra pass's detection signal.
Worst-case complexity. O(V⋅E): up to V−1 passes (no early exit possible when a genuine negative cycle exists, since some edge always still improves), each inspecting all E edges once, plus the fixed-cost detection pass.
Worked example
A 5-node graph: 0→1 (weight 1), then a cycle 1→2→3→4→1 with weights −1,−1,−1,2, summing to −1 (negative).
Tracing distance to node 1 across passes, verified by actually running the algorithm rather than
hand-waving the per-pass numbers (edges relax in insertion order 0,1,2,3,4 within each pass, which matters: it
lets a single pass's updates cascade further around the cycle than a naive "one edge per pass" intuition would
suggest):
def bellman_ford_traced(graph, source):
dist = {u: float("inf") for u in graph}
pred = {u: None for u in graph}
dist[source] = 0
V = len(graph)
trace = []
for p in range(V - 1):
changed = False
for u in graph:
if dist[u] == float("inf"):
continue
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
changed = True
trace.append(dict(dist))
if not changed:
break
culprit = None
for u in graph:
if dist[u] == float("inf"):
continue
for v, w in graph[u]:
if dist[u] + w < dist[v]:
culprit = v
break
if culprit is not None:
break
return trace, culprit is not None
g = {0: [(1, 1)], 1: [(2, -1)], 2: [(3, -1)], 3: [(4, -1)], 4: [(1, 2)]}
trace, has_cycle = bellman_ford_traced(g, 0)
for i, d in enumerate(trace, 1):
print(f"after pass {i}: dist[1]={d[1]}")
print("negative cycle detected on the extra pass:", has_cycle)
Output (actually executed with python3):
after pass 1: dist[1]=0
after pass 2: dist[1]=-1
after pass 3: dist[1]=-2
after pass 4: dist[1]=-3
negative cycle detected on the extra pass: True
dist[1] reaches 0, not 1, after pass 1: because edges are relaxed in the fixed order 0,1,2,3,4 within a single
pass, pass 1 already walks all the way around the cycle once (0->1 sets dist[1]=1, then 1->2, 2->3, 3->4 propagate
forward, then 4->1 closes the loop and pulls dist[1] back down to 0 within that SAME pass). From pass 2 onward
each additional pass subtracts another 1 as the cycle's net -1 keeps being re-applied, and the extra (5th) pass
still finds an edge to relax, correctly flagging a negative cycle. This is the actual, executed behavior on this
graph, not an estimate: a hand trace that assumes exactly one edge's worth of progress per pass (as an earlier
draft of this answer did) undercounts how far a single pass can propagate when the edge-processing order happens
to align with the cycle's direction, though the qualitative conclusion, distances keep decreasing without bound
and the extra pass detects it, is unaffected by that undercounting.
Trade-offs and pitfalls
- Scaling negative-cycle detection for massive graphs with limited memory.
- Source partitioning. Bellman-Ford as described detects cycles reachable from ONE source. For massive graphs, run it from a small set of strategically chosen sources (for example, one per connected component, or per known high-fan-out hub) rather than from every vertex; this trades completeness (a cycle unreachable from any chosen source is missed) for a large constant-factor reduction in total work, which is often an acceptable trade when the goal is "catch cycles that would actually affect real traffic," not "prove the whole graph is cycle-free."
- Sampling. On a graph believed to be usually well-formed (cycles are rare bugs, not expected structure, such as a dependency graph or a currency-arbitrage graph most of the time), running full detection on a random subset of edges' surrounding neighborhoods each cycle, rather than the whole graph every time, catches cycles probabilistically over repeated runs while bounding per-run cost; this is a monitoring posture (catch it eventually, cheaply, repeatedly) rather than a one-shot correctness guarantee.
- Early-termination heuristics. The standard
if not changed: breakoptimization terminates the moment a pass makes no improvement, which is the common case on real, cycle-free graphs; combined with tracking only the SUBSET of vertices whose distance changed on the previous pass (rather than re-scanning all E edges every pass, an optimization sometimes called SPFA, shortest path faster algorithm), this reduces typical-case work substantially, though the worst-case O(VE) bound remains for adversarial or genuinely cyclic input. - Streaming/partitioned memory strategies. For a graph too large to hold in memory at once, partition vertices across machines and run Bellman-Ford's edge-relaxation passes as a distributed message-passing computation (each partition relaxes its local edges and forwards updated distances for cross-partition edges), a pattern that maps naturally onto systems like Pregel-style graph processing frameworks; this changes the constant factors and adds network cost per pass but preserves the same pass-count guarantee.
- Common mistake: assuming sampling or source-partitioning give the same GUARANTEE as full Bellman-Ford. They trade a hard correctness guarantee for a probabilistic or scoped one; a system that needs a hard guarantee (rejecting a deployment plan, for example) should not silently swap in a sampled check without making that trade-off explicit to whoever consumes the result.
- Common mistake: conflating "no negative cycle found by my source-limited or sampled check" with "no negative cycle exists in the graph." These heuristics reduce false negatives' PROBABILITY, they do not eliminate the possibility, and reporting them with the same confidence as a full run misrepresents what was actually verified.
For the following scenarios choose the most appropriate shortest-path algorithm and justify your choice: (a) city road routing with non-negative weights and frequent queries, (b) currency exchange graph where arbitrage implies negative cycles, (c) computing pairwise social network distances on unweighted graphs. Include complexity and practical concerns.
Sample Answer
Direct answer
(a) City road routing with non-negative weights and frequent repeated queries: Dijkstra's algorithm as the baseline, but for a system serving many queries against a largely static road network, layer on precomputation (Contraction Hierarchies or a bidirectional/ALT search) rather than running plain Dijkstra fresh per query. (b) A currency exchange graph where arbitrage implies negative cycles: Bellman-Ford, specifically because it is the standard algorithm that both handles negative edge weights and can detect a negative cycle's existence, which is the actual signal being searched for (an arbitrage opportunity IS a negative cycle in a graph where edge weights are the negative log of exchange rates). (c) Pairwise social network distances on unweighted graphs: breadth-first search (BFS) from each source, since with unweighted edges the fewest-edges path IS the shortest path, and BFS finds it in strictly less work than any weighted algorithm would need to do.
Structured elaboration
(a) City road routing. Every edge weight is non-negative (travel time or distance cannot be negative), which is exactly Dijkstra's precondition. For a ONE-OFF query, plain Dijkstra with a binary heap is O((V+E)logV) and is the right default. For a system answering MANY queries against a road network that changes rarely (new roads open occasionally; traffic-based weight updates happen far more often than the topology itself changes), the standard production approach precomputes shortcuts once (Contraction Hierarchies) so that individual queries run in a fraction of the cost of a from-scratch Dijkstra, or uses bidirectional search (searching simultaneously from both source and destination and stopping when the two frontiers meet) to roughly halve the effective search radius. The key judgment call the question is testing: recognizing that "frequent queries" changes the right answer from "which single-query algorithm" to "what should be precomputed once, before any query arrives."
(b) Currency arbitrage. Model each currency as a node and each exchange rate as a directed edge weighted by −log(rate). Under this transform, a product of exchange rates greater than 1 (a profitable arbitrage loop) becomes a SUM of edge weights less than 0 (a negative cycle), because log turns multiplication into addition and the sign flip turns "greater than 1" into "less than 0." Dijkstra cannot be used here at all: it assumes non-negative weights and produces silently wrong results (not even a detectable error) if given negative edges, because its greedy "finalize the closest unvisited node" strategy assumes no later relaxation could ever improve an already-finalized node, an assumption negative edges break. Bellman-Ford handles negative edges correctly by relaxing every edge up to V−1 times, and its cycle-detection extension (checking whether any edge can still be relaxed on a V-th pass) is exactly the mechanism for detecting that a negative cycle, and therefore an arbitrage opportunity, exists.
(c) Unweighted social-network distances. With every edge implicitly weight 1, Dijkstra still gives the correct answer but does unnecessary work maintaining a priority queue and comparing distances that could only ever increase by exactly 1 per edge. BFS achieves the same correct shortest-path distances using a plain FIFO queue, exploiting the fact that BFS naturally visits nodes in increasing order of edge count, which is precisely the shortest-path order when every edge costs the same.
Worked example
Complexity comparison, V = number of nodes, E = number of edges:
| Scenario | Algorithm | Time | Why this and not the others |
|---|---|---|---|
| (a) road routing, repeated queries | Dijkstra (single query) / Contraction Hierarchies (repeated) | O((V+E)logV) per query, or a fraction of that after one-time CH preprocessing | Bellman-Ford would work but costs O(VE), strictly worse for non-negative weights with no compensating benefit; BFS is wrong here since edges are weighted |
| (b) currency arbitrage | Bellman-Ford | O(VE) | Dijkstra silently breaks under negative edges (not just slower, actually WRONG); BFS is wrong since edges are weighted (log-rates), not unit cost |
| (c) unweighted social distances | BFS | O(V+E) per source | Both Dijkstra and Bellman-Ford give the correct answer but do asymptotically or constant-factor more work than necessary for a uniform-cost graph |
Concrete arbitrage instance for (b): three currencies USD, EUR, JPY with exchange rates USD to EUR = 0.9, EUR to JPY = 130, JPY to USD = 0.0086. The round-trip product is 0.9×130×0.0086=1.0062, greater than 1, meaning one unit of USD converted around the full loop back to USD returns 1.0062 units, a 0.62 percent arbitrage. Under the negative-log transform: edge weights become −ln(0.9)≈0.1054, −ln(130)≈−4.8675, −ln(0.0086)≈4.7560, summing to 0.1054−4.8675+4.7560=−0.0061, which matches −ln(1.0062)≈−0.0062 (the small residual is rounding in the 4-decimal edge weights). A negative cycle total, matching the arbitrage: a negative sum of log-weights corresponds to a product greater than 1.
Trade-offs and pitfalls
- Common mistake: reaching for Dijkstra in scenario (b) because "it's the standard shortest-path algorithm." Dijkstra's core greedy step, permanently finalizing the shortest known distance to a node once popped, is provably wrong in the presence of negative edges, since a later negative edge could still improve a distance that was already treated as final. This is not a performance trade-off, it is a correctness failure, and it fails silently (no exception, no error) rather than crashing, which makes it a genuinely dangerous mistake to make in a financial context.
- Common mistake: reaching for Bellman-Ford in scenario (c) "to be safe." It gives the correct answer but at O(VE) instead of BFS's O(V+E), a real cost difference at scale on a large social graph, for no benefit since there are no negative weights to worry about.
- Common mistake in scenario (a): treating "frequent queries" as irrelevant to the algorithm choice. A system that reruns plain Dijkstra from scratch for every query is leaving a large, well-known optimization on the table (precomputation amortized across queries) that specifically becomes worthwhile once query volume is high enough to justify the one-time preprocessing cost.
- The negative-cycle DETECTION step in scenario (b) is not optional flavor, it is the actual point of the exercise: finding shortest paths in a graph that HAS a negative cycle is not even well-defined (you could loop the cycle infinitely to make the "shortest path" arbitrarily negative), so the correct behavior is to detect and report the cycle's existence, not to return some finite distance as if the graph were well-behaved.
Implement bidirectional BFS to find the shortest path in an unweighted graph between s and t. Provide a Python implementation sketch, explain correctness, expected speedup on large sparse graphs, and describe worst-case behavior. Discuss how to merge frontiers and reconstruct the path.
Sample Answer
Direct answer
Plain breadth-first search (BFS) from a single source grows a "ball" of radius d (the shortest distance) that covers on the order of bd nodes, where b is the graph's typical branching factor. Bidirectional BFS instead grows two smaller balls, one from s and one from t, alternately expanding whichever frontier is smaller, and stops the instant the two frontiers touch. Because each ball only needs to reach roughly half the distance, this covers on the order of 2bd/2 nodes instead of bd, an exponential reduction in the branching factor's exponent for large sparse graphs, even though both approaches remain O(V+E) in the absolute worst case.
Structured elaboration
Correctness rests on one fact: standard single-source BFS finalizes a node's distance the instant it is first discovered, because it explores in non-decreasing distance order. Running two such searches at once, one following forward edges from s and one following forward edges from t (equivalently, following reverse edges from t if the graph is directed), preserves that property independently on each side. The meeting point is the first node discovered by either search that the other search has already discovered; at that moment, the distance from s to the meeting point plus the distance from the meeting point to t is provably the shortest s-to-t distance, because both partial distances are themselves shortest (by the single-source BFS guarantee) and no shorter path could exist that this pair of expanding balls would have missed, since the balls' union covers every node within their respective, jointly-sufficient radii.
Merging frontiers and reconstructing the path. Keep two parent maps, one per direction. When a node discovered from the s side turns out to already be a key in the t side's parent map (or vice versa), that node is the meeting point: walk parent_f backward from the meeting point to s (giving the first half in reverse, then reversed to forward order), and walk parent_b backward from the meeting point's t-side predecessor to t (giving the second half directly), then concatenate.
Expand the smaller frontier, always. This is what actually delivers the speedup: if one side always expanded regardless of the other's size, an adversarial graph (dense near s, sparse near t) could force one side to do almost all the work anyway. Balancing by picking the smaller frontier at each step keeps both sides' work close to symmetric.
Worked example
from collections import deque
from typing import Dict, List
def bidirectional_bfs(adj: Dict[int, List[int]], s: int, t: int) -> List[int]:
# Bidirectional BFS: expand a frontier from s and a frontier from t in
# lockstep, always growing whichever frontier is smaller, stopping the
# instant the two visited sets share a node. Returns the shortest path
# from s to t inclusive, or [] if none exists.
if s == t:
return [s]
if s not in adj or t not in adj:
return []
parent_f = {s: None}
parent_b = {t: None}
frontier_f = {s}
frontier_b = {t}
def expand(frontier, parent, other_parent):
next_frontier = set()
for u in frontier:
for v in adj.get(u, []):
if v not in parent:
parent[v] = u
if v in other_parent:
return v
next_frontier.add(v)
frontier.clear()
frontier.update(next_frontier)
return None
meet = None
while frontier_f and frontier_b and meet is None:
if len(frontier_f) <= len(frontier_b):
meet = expand(frontier_f, parent_f, parent_b)
else:
meet = expand(frontier_b, parent_b, parent_f)
if meet is None:
return []
left = []
node = meet
while node is not None:
left.append(node)
node = parent_f[node]
left.reverse()
right = []
node = parent_b[meet]
while node is not None:
right.append(node)
node = parent_b[node]
return left + right
if __name__ == "__main__":
n = 20
adj = {i: [] for i in range(n)}
for i in range(n - 1):
adj[i].append(i + 1)
adj[i + 1].append(i)
path = bidirectional_bfs(adj, 0, 19)
print("Shortest path 0 -> 19 on a 20-node chain:", path)
print("Path length (edges):", len(path) - 1)
def is_valid_path(path, adj):
return all(path[i+1] in adj[path[i]] for i in range(len(path)-1))
print("Path uses only real edges:", is_valid_path(path, adj))
def bfs_dist(adj, s, t):
dist = {s: 0}
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist.get(t)
ref = bfs_dist(adj, 0, 19)
print("Matches independent single-source BFS distance:", len(path) - 1 == ref)
adj_disc = {0: [1], 1: [0], 2: [3], 3: [2]}
print("0 -> 3 (disconnected):", bidirectional_bfs(adj_disc, 0, 3))
print("5 -> 6 (unreachable, unknown nodes):", bidirectional_bfs(adj_disc, 5, 6))
Output (actually executed with python3):
Shortest path 0 -> 19 on a 20-node chain: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Path length (edges): 19
Path uses only real edges: True
Matches independent single-source BFS distance: True
0 -> 3 (disconnected): []
5 -> 6 (unreachable, unknown nodes): []
Complexity
Time O(V+E) in the worst case, identical to plain single-source BFS, but the constant that matters in practice is how many nodes each side actually visits before meeting: roughly O(bd/2) per side for branching factor b and true distance d, versus O(bd) for a single expanding frontier. Space O(V) for the two parent maps and two frontier sets combined.
Edge cases
s == t: returns[s]immediately, a zero-edge path, without ever entering the expansion loop.sortmissing fromadj: returns[]rather than raising.- Disconnected graph: both frontiers eventually empty without ever meeting; the
while frontier_f and frontier_b and meet is Noneloop condition catches this and falls through toreturn []. sandtalready adjacent: the very first expansion (from whichever side goes first) discovers the other directly, since checkingif v in other_parenthappens on every single node discovery, not only after a full frontier finishes.
Trade-offs and pitfalls
- Worst-case behavior. In a dense graph, or when
sandtare actually close together, bidirectional BFS carries real constant-factor overhead (managing two parent maps, two frontiers, and a meeting-point check on every expansion) that plain single-source BFS does not, for the same asymptotic O(V+E) bound; the technique earns its keep specifically on large, sparse graphs with a genuinely long shortest distance, which is exactly the regime where bd/2≪bd has real teeth. - Directed graphs need explicit reverse adjacency. The sketch above uses one shared
adjfor both directions, which is only correct for an undirected graph (or a directed graph the caller has already prepared with both a forward and a reverse adjacency list). For a directed graph, thet-side expansion must walk edges backward (who points to me), which requires a separate reverse-adjacency structure, not the same forward list reused. - Common mistake: checking for a meeting point only after a whole frontier finishes expanding, rather than the instant a shared node is discovered mid-expansion. Waiting until an entire frontier finishes can overshoot: it may discover several nodes deeper than the true meeting point before noticing the overlap, silently returning a path one or more edges longer than necessary. The
expandhelper above checksif v in other_parentper-node, inside the loop, specifically to avoid this. - Common mistake: always expanding the
sside (or always the smaller-labeled side) regardless of current frontier size. This defeats the entire point of the technique: the speedup comes from keeping both expanding regions roughly balanced, not merely from having two searches running. - Near-identical bidirectional BFS implementations show up repeatedly across very different engineering contexts, all converging on the same shape (parent maps plus a smaller-frontier-first expansion rule), which is a good sign this really is the canonical technique, not one team's idiosyncratic approach.
Formally derive the time and space complexity of BFS and DFS on graphs represented as (a) adjacency list and (b) adjacency matrix. Show how the number of edge inspections leads to O(V+E) for adjacency lists and O(V^2) for adjacency matrices. Discuss directed vs undirected differences and assumptions about visiting implementation details (e.g., iterators).
Sample Answer
Direct answer
Both breadth-first search (BFS) and depth-first search (DFS) run in O(V+E) time on an adjacency list, because the total work is bounded by the number of vertices touched plus the total number of neighbor-pointer traversals across the whole run, which sums to exactly E (or 2E for an undirected graph, still O(E)). On an adjacency matrix, both run in O(V2), because finding a vertex's neighbors means scanning its entire row of V entries regardless of how many of them are actually edges, and this happens for every vertex.
Structured elaboration
Adjacency list derivation. Let visited[] track which vertices have been processed, guaranteeing each vertex is expanded at most once.
- Per-vertex overhead: each of the V vertices is enqueued/pushed and dequeued/popped at most once, each operation O(1) amortized, contributing Θ(V) total.
- Per-edge overhead: when a vertex u is processed, the algorithm iterates its adjacency list, one step per neighbor. Summed across every vertex processed during the traversal, this equals the total number of adjacency-list entries touched. For a directed graph, ∑vdeg+(v)=E (every edge appears exactly once, in its source's list). For an undirected graph, ∑vdeg(v)=2E (every edge appears once in each endpoint's list), still Θ(E) since the factor of 2 is a constant.
- Total: Θ(V)+Θ(E)=Θ(V+E).
- Why an edge is inspected only a constant number of times:
visited[]ensures a vertex's adjacency list is scanned exactly once (when that vertex itself is dequeued/popped), not once per incoming edge; without this guard, a vertex reachable by many edges could have its list rescanned redundantly.
Adjacency matrix derivation.
- Per-vertex overhead: identical to the list case, Θ(V) for enqueue/dequeue bookkeeping.
- Per-edge overhead: finding vertex u's neighbors means scanning row u of the V×V matrix, V cell checks, REGARDLESS of how many of those cells are actually 1 (an edge). This happens once per processed vertex, giving V vertices × V cells each =Θ(V2).
- Total: Θ(V)+Θ(V2)=Θ(V2), dominated entirely by the per-vertex row scan; the matrix's time bound does not depend on E at all, sparse or dense.
Directed versus undirected. The derivation's shape is identical for both; the only difference is the constant factor in the edge-count term (E for directed, 2E for undirected in the list case; the matrix case is unaffected either way since a full row is scanned regardless of the graph's directedness, though an undirected adjacency matrix is symmetric, which some implementations exploit to only store, though not necessarily to only SCAN, roughly half the entries).
Assumptions about the visiting mechanism. This analysis assumes iterating a vertex's adjacency list (or a matrix row) costs O(1) per element visited, true for a plain array, a linked list, or a language iterator with O(1) amortized next(). If neighbors were instead stored in a structure with a more expensive per-element access cost (a balanced tree ordered by neighbor id, for instance, used to support fast edge-existence checks), the per-edge term would pick up an extra O(logdeg(v)) factor, changing the bound to O(V+Elog(avg degree)); the classic O(V+E) result specifically assumes the cheapest reasonable neighbor-storage structure, not any adjacency-list variant whatsoever.
Worked example
Take V=1000, and consider two graphs on that vertex set: a sparse one with E=2000 (average degree 4) and a dense one with E=400,000 (close to the V(V−1)/2≈499,500 maximum for an undirected simple graph).
Adjacency-list time is Θ(V+E): 1000+2000=3000 "units" of work for the sparse graph, 1000+400,000=401,000 units for the dense one, work that scales directly with how many real edges exist.
Adjacency-matrix time is Θ(V2)=10002=1,000,000 units of work for BOTH graphs, since the matrix traversal cost never looks at E at all. For the sparse graph, the matrix does roughly 333x MORE work than the list (1,000,000 vs 3,000); for the dense graph, the gap narrows sharply but does NOT invert: the list's 401,000 units is still fewer than the matrix's 1,000,000, about 2.5x less. This is not an artifact of the chosen numbers: for ANY simple graph (no self-loops or parallel edges), E is bounded by V(V−1)/2, so V+E is bounded by V(V+1)/2≈V2/2, always roughly HALF of the matrix's V2, even at the maximum possible density (at V=1000's true max, E=499,500, list work is 500,500 versus the matrix's 1,000,000, still about 2x less). The list's raw operation count can never actually exceed the matrix's for a full traversal of a simple graph; there is no density at which this accounting makes the matrix outright faster. What DOES happen as E approaches V2 is that the list's ASYMPTOTIC advantage evaporates (both become Θ(V2)), which is why dense-graph implementations reach for the matrix anyway: not because it traverses faster, but because its better constant factors, contiguous memory with strong cache locality, a simpler implementation, and O(1) point edge-existence checks the list cannot match, are worth more once the list's shrinking speed edge is no longer an order-of-magnitude win.
Trade-offs and pitfalls
- Common mistake: assuming the O(V+E) vs O(V2) comparison means the list is dramatically faster at every density, OR (the opposite, equally wrong error) that a genuinely dense graph flips the ordering and makes the matrix faster in raw traversal work. Neither extreme is right: for a simple graph the list's operation count can never exceed roughly V2/2, so it never actually loses this race, but its margin shrinks from over 300x at low density to under 3x near maximum density, which is why dense-graph code often reaches for the matrix anyway, not because it got faster, but because the list's shrinking advantage stops being worth its extra implementation complexity once cache locality and O(1) edge lookups are on the table.
- Common mistake: treating O(V+E) as automatically implying the algorithm is "linear." It is linear in the SIZE OF THE INPUT (which is itself Θ(V+E) for an adjacency list), not linear in V alone; a graph where E grows quadratically in V makes the traversal quadratic too, list or no list.
- The visited-array guard is what makes the list bound tight, not incidental to it. Removing it (allowing a vertex's adjacency list to be rescanned every time any neighbor points to it) would make the bound O(V⋅E) in the worst case (a densely-interconnected graph revisiting the same expensive vertex repeatedly), which is exactly the kind of subtle omission that turns a correct asymptotic claim into a wrong one.
- Space follows the same split: adjacency list is Θ(V+E) (proportional to what actually exists), matrix is Θ(V2) (fixed regardless of edge count), independent of the traversal algorithm's own O(V) queue/stack overhead, which is the same for both representations.
Implement a multi-source BFS in Python. Input: n (number of nodes 0..n-1), edges list for an undirected unweighted graph, and a list of source nodes. Return an integer array dist of length n where dist[v] is the minimum number of edges from v to the nearest source, or -1 if unreachable. Your solution must run in O(V + E) time and use O(V) extra space.
Sample Answer
Direct answer
Seed a single breadth-first search (BFS) queue with all source nodes at distance 0 simultaneously, rather than running BFS once per source and taking the minimum. Because BFS explores in strict distance order, the first time any node is reached from ANY source is guaranteed to be its true minimum distance to the nearest source, so one pass over every vertex and edge suffices.
Structured elaboration
The key insight is that a standard single-source BFS's correctness argument, the first time a node is dequeued its distance is final, does not depend on there being only one source in the queue at the start. Seeding multiple sources at distance 0 just means the frontier expands outward from several points at once; distances still increase monotonically layer by layer, so a node discovered from source A at distance 3 and also reachable from source B at distance 5 will correctly end up recorded at distance 3, whichever source's expansion reaches it first, since BFS explores layer 3 (from either source) entirely before layer 4.
This avoids the alternative of running BFS once per source and taking an elementwise minimum, which costs O(k⋅(V+E)) for k sources instead of a single O(V+E) pass.
Worked example
from collections import deque
from typing import List
def multi_source_bfs(n: int, edges: List[List[int]], sources: List[int]) -> List[int]:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
dist = [-1] * n
q = deque()
for s in set(sources):
if 0 <= s < n and dist[s] == -1:
dist[s] = 0
q.append(s)
while q:
u = q.popleft()
for v in adj[u]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
return dist
if __name__ == "__main__":
# n=8 undirected graph: a 6-cycle over nodes 0..5, plus a separate isolated pair 6-7
n = 8
edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[0,5],[6,7]]
sources = [0, 4]
dist = multi_source_bfs(n, edges, sources)
print("dist:", dist)
# verify against brute force: minimum over independent single-source BFS runs
def bfs_from(src):
d = [-1]*n
adj = [[] for _ in range(n)]
for u,v in edges:
adj[u].append(v); adj[v].append(u)
d[src]=0
qq=deque([src])
while qq:
u=qq.popleft()
for v in adj[u]:
if d[v]==-1:
d[v]=d[u]+1
qq.append(v)
return d
d0, d4 = bfs_from(0), bfs_from(4)
expected = [min(a,b) if a!=-1 and b!=-1 else (a if a!=-1 else b) for a,b in zip(d0,d4)]
print("expected (min of independent single-source runs):", expected)
print("matches:", dist == expected)
print("unreachable nodes 6 and 7 both -1:", dist[6]==-1 and dist[7]==-1)
Output (actually executed with python3):
dist: [0, 1, 2, 1, 0, 1, -1, -1]
expected (min of independent single-source runs): [0, 1, 2, 1, 0, 1, -1, -1]
matches: True
unreachable nodes 6 and 7 both -1: True
Complexity
- Time: O(V+E), each vertex is dequeued once and each edge is examined at most twice (once from each endpoint).
- Space: O(V) for the adjacency list construction, the
distarray, and the queue.
Edge cases
- No sources given:
diststays all-1, no error, since thefor s in set(sources)loop simply does not run. - A source index outside
[0, n): silently ignored via the bounds check, rather than crashing on an out-of-range list access. - Disconnected components not reachable from any source: correctly left at
-1, handled naturally since BFS only expands from the seeded frontier. - Duplicate sources: deduplicated via
set(sources)so a repeated source does not enqueue the same starting node twice.
Trade-offs and pitfalls
- Common mistake: running BFS independently once per source and taking the minimum. This gives the same answer but costs O(k⋅(V+E)) instead of O(V+E), a real difference once k (the number of sources) is large, for example this shape shows up as "distance to nearest fire station," "distance to nearest rotten orange," or "distance to nearest cache node."
- Common mistake: initializing all sources into the queue but forgetting to check
dist[v] == -1before overwriting on relaxation, which would let a later, longer path stomp an earlier, shorter one; the-1sentinel check is what preserves BFS's "first time reached is shortest" guarantee. - Extending this to a directed graph only requires building
adjfrom directed edges (drop the reverse insert); the algorithm's correctness argument (layer-by-layer expansion) is unaffected by directedness. - This does NOT generalize directly to weighted graphs with varying positive weights; that requires a priority queue and becomes multi-source Dijkstra, not multi-source BFS, since BFS's "distance equals number of edges" property depends on every edge costing exactly 1.
Unlock Full Question Bank
Get access to all Graphs and Graph Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.