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.
Design algorithms and practical system approaches to maintain connectivity information (connected components) under dynamic edge insertions and deletions for an undirected graph. Discuss amortized complexities, use of union-find for insertions, difficulties with deletions, and practical engineering tradeoffs such as batching deletes or full rebuilds. Suggest a strategy suitable for near-real-time dashboards.
Sample Answer
Direct answer
Maintaining connected components under insertions alone is a solved, cheap problem: Union-Find handles it in amortized O(α(n)) per insertion. Deletions are the genuinely hard part, because Union-Find's tree-merging structure has no efficient inverse: once two sets are merged, there is no cheap way to ask "if I remove this one edge, does the merged set need to split back into two." The practical engineering answer is almost never "support arbitrary deletions with full generality," it is to constrain the problem: batch deletions and periodically rebuild, or accept an offline model where the full sequence of operations is known in advance, or reach for a genuinely dynamic data structure (Euler tour trees, link-cut trees) only when the deletion rate and latency requirements truly demand it.
Structured elaboration
Why insertions are easy. Each new edge is one union call. Amortized cost per operation is O(α(n)), and the structure never needs to "undo" anything to support more insertions, so an insert-heavy or insert-only workload is a non-issue for Union-Find.
Why deletions are hard. When an edge is removed, the two nodes it connected might still be connected through some OTHER path (so nothing changes), or that edge might have been the only path between two halves of what is now two separate components (so the structure must split). Union-Find's tree shape after path compression has discarded the information needed to tell these two cases apart cheaply: it only remembers "these nodes ended up under the same root at some point," not "here is the specific set of edges that currently justifies that." Determining which case applies in general requires re-deriving connectivity from the remaining edges, which is exactly the expensive operation Union-Find was built to avoid.
Three practical strategies, in order of increasing sophistication:
- Full rebuild on every batch of deletions. Accumulate deletions for some time window or count threshold, then rebuild the entire Union-Find structure from the current live edge set. Cost: O(E) per rebuild, amortized over however many deletions triggered it. This is the simplest strategy and is often sufficient when connectivity queries can tolerate being slightly stale (answered against the last completed rebuild) rather than reflecting every deletion instantly.
- Offline divide-and-conquer with rollback, when the full sequence of insertions, deletions, and queries is known ahead of time (a genuinely offline setting, common in batch analytics jobs). Each edge's active time interval is computed in advance, and a Union-Find variant that supports undoing unions (by NOT using path compression, only union by size, and keeping an explicit undo stack) processes the timeline via a segment tree over time, applying and rolling back unions as it recurses. This achieves O((V+E+Q)logT) total for T time steps and Q queries, at the cost of needing the full operation sequence upfront, which rules it out for a genuinely live, open-ended stream.
- Fully dynamic connectivity structures (Euler tour trees, or the Holm-de Lichtenberg-Thorup structure), which support both insertion and deletion in O(log2n) amortized time without needing the future operation sequence in advance. These exist and are the theoretically correct answer to "support both directions online," but they carry real implementation complexity (multiple levels of spanning-forest bookkeeping) well beyond what most production systems justify building or maintaining in-house.
Amortized complexity summary:
| Strategy | Insert | Delete | Query | Needs future ops known? |
|---|---|---|---|---|
| Plain Union-Find | O(α(n)) | not supported | O(α(n)) | No |
| Batched rebuild | O(α(n)) | O(E/B) amortized over a batch of B deletions | O(α(n)) against last rebuild | No |
| Offline divide-and-conquer w/ rollback | O(logT) amortized | O(logT) amortized | O(logT) amortized | Yes |
| Fully dynamic (Euler tour tree) | O(log2n) amortized | O(log2n) amortized | O(logn) | No |
Worked example
For a near-real-time dashboard showing which servers are currently mutually reachable (an operational monitoring use case), a reasonable strategy is strategy 1, tuned: rebuild the Union-Find structure on a fixed cadence (say, once per minute, driven by the dashboard's own refresh interval, not by a fixed edge count) from the live edge set as of that moment, and serve all connectivity queries against the most recent rebuild in between. If a specific incident-response workflow needs connectivity reflecting deletions within seconds rather than up to a minute of staleness, that workflow can additionally maintain its OWN small Union-Find rebuilt just over the specific subgraph relevant to the incident, rather than paying the cost of low-latency full dynamic connectivity across the entire graph. The batching threshold (time-based vs count-based) is a product/operational decision, not a purely algorithmic one: a time-based cadence gives predictable staleness bounds, while a count-based cadence (rebuild after every B deletions) gives a predictable amortized cost per deletion but an unpredictable staleness bound if deletions arrive in bursts.
Trade-offs and pitfalls
- Common mistake: reaching for a fully dynamic connectivity structure by default. These are real, correct, and asymptotically strong, but the implementation complexity is high enough that most production systems are better served by batching plus a staleness bound the business can actually tolerate; reserve the fully dynamic structure for cases where sub-second correctness after every single deletion is a hard requirement, not a nice-to-have.
- Common mistake: conflating "offline" (full operation sequence known in advance) with "batched" (deletions grouped into windows, but the future is still unknown). The divide-and-conquer-with-rollback technique needs the FULL timeline upfront; it cannot be run incrementally against a live, open-ended stream, which makes it a poor fit for a live dashboard and a good fit for a nightly batch-analytics reprocessing job over a day's worth of logged topology changes.
- A rebuild-based strategy's staleness bound is a first-class design parameter, not an afterthought: it must be stated and monitored (rebuild latency drifting up as the graph grows is a real operational risk), not left as an implicit assumption that "the rebuild is fast enough."
- Query semantics need to be explicit about what "connected" means during a batching window: does a query answered mid-batch reflect the edges as of the LAST completed rebuild, or does it block until the next rebuild finishes? Silently mixing the two within one system produces confusing, non-reproducible answers to the same query asked moments apart.
Implement breadth-first search (BFS) in Python to find the shortest path between two nodes in an unweighted graph. Function signature: def shortest_path(adj: Dict[int, List[int]], start: int, target: int) -> List[int]. Return the list of nodes forming the shortest path from start to target inclusive, or an empty list if no path exists. The adjacency input is an adjacency list mapping node ids to neighbor lists. Aim for O(V+E) time and O(V) memory.
Sample Answer
Direct answer
Breadth-first search (BFS) finds the shortest path between two nodes in an unweighted graph because it explores the graph in strict distance order: it fully visits every node at distance 1 from the start before touching any node at distance 2, and so on. The first time any node is reached, that is necessarily via the fewest possible edges, so recording each node's discoverer (its parent) as it is first visited, then walking those parent pointers backward from the target, reconstructs a shortest path in O(V+E) time and O(V) space.
Structured elaboration
Two pieces of state drive the algorithm: a visited set (or equivalently, a parent dict whose keys double as the visited set) to guarantee each node is processed once, and the parent map itself to allow path reconstruction. A first-in-first-out (FIFO) queue guarantees the "distance order" property: the queue always contains nodes from at most two contiguous distance layers at a time, and everything from the current layer is dequeued before anything from the next layer is examined.
Worked example
from collections import deque
from typing import Dict, List
def shortest_path(adj: Dict[int, List[int]], start: int, target: int) -> List[int]:
# BFS shortest path in an unweighted graph. Returns the node list from
# start to target inclusive, or [] if target is unreachable.
if start == target:
return [start]
if start not in adj:
return []
visited = {start}
parent = {start: None}
q = deque([start])
while q:
u = q.popleft()
for v in adj.get(u, []):
if v not in visited:
visited.add(v)
parent[v] = u
if v == target:
q.clear()
break
q.append(v)
if target not in parent:
return []
path = []
node = target
while node is not None:
path.append(node)
node = parent[node]
path.reverse()
return path
if __name__ == "__main__":
adj = {
0: [1, 2],
1: [0, 3],
2: [0, 3],
3: [1, 2, 4],
4: [3],
5: [6], # disconnected component
6: [5],
}
print("0 -> 4:", shortest_path(adj, 0, 4))
print("0 -> 5 (unreachable):", shortest_path(adj, 0, 5))
print("0 -> 0 (same node):", shortest_path(adj, 0, 0))
print("7 -> 1 (start not in graph):", shortest_path(adj, 7, 1))
def bfs_distance(adj, start, target):
dist = {start: 0}
q = deque([start])
while q:
u = q.popleft()
for v in adj.get(u, []):
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist.get(target)
p = shortest_path(adj, 0, 4)
ref_dist = bfs_distance(adj, 0, 4)
print("Path edges match independently computed BFS distance:", len(p) - 1 == ref_dist, f"(path edges={len(p)-1}, ref_dist={ref_dist})")
Output (actually executed with python3):
0 -> 4: [0, 1, 3, 4]
0 -> 5 (unreachable): []
0 -> 0 (same node): [0]
7 -> 1 (start not in graph): []
Path edges match independently computed BFS distance: True (path edges=3, ref_dist=3)
The bfs_distance helper is a separate, minimal BFS that only ever tracks distances, never a path; it exists purely to cross-check the path-returning function's length against an independently computed ground truth, and the two agree.
Complexity
Time O(V+E): each node is enqueued and dequeued at most once, and each edge is examined at most once from each of its endpoints (twice total for an undirected graph, once for a directed graph). Space O(V) for visited and parent, plus the queue, which never holds more nodes than exist at the two frontier layers being processed.
Edge cases
start == target: returns[start]immediately, a path of length zero (no edges), handled as a special case up front rather than relying on the traversal to "discover" the start node as its own neighbor.startnot present inadj: returns[]rather than raising, treating an unknown start node the same as "no path exists."- Disconnected
target: the BFS frontier exhausts without ever reachingtarget;target not in parentcatches this and returns[]. - Multiple shortest paths of equal length: BFS returns one of them, determined by adjacency-list iteration order, not necessarily a "canonical" one; if a caller needs a specific tie-break (lexicographically smallest node sequence, for example), that requires sorting each node's neighbor list before traversal.
- Early exit on discovering the target: the
q.clear(); breakpair stops further expansion the instant the target is first discovered, since BFS guarantees that first discovery is already a shortest path; continuing to explore further nodes would waste work without changing the answer.
Trade-offs and pitfalls
- Common mistake: marking a node visited when it is dequeued rather than when it is first enqueued (discovered). If two different frontier nodes both point to the same not-yet-visited neighbor before either is dequeued, dequeue-time marking lets that neighbor be enqueued twice, wasting work and, worse, letting the second enqueue silently overwrite
parentwith a different, equally-short but different, predecessor, which is harmless for path length but can produce a different (still valid) path than intended if the caller expects determinism. - Common mistake: using depth-first search (DFS) instead of BFS for this task. DFS also visits every reachable node, but it does not explore in non-decreasing distance order, so the first path DFS finds to
targetis not guaranteed to be shortest; DFS proves reachability, not shortest distance, in an unweighted graph. - A commonly asked variant of this same archetype returns a distance MAP (
{node: distance}for every reachable node) instead of a single path. That variant is a strict generalization: thebfs_distancehelper above is essentially that function with the path-reconstruction machinery stripped out, and a caller who needs distances to many targets from one source should prefer running that once rather than callingshortest_pathrepeatedly, which would redundantly re-traverse shared prefixes of the graph on every call. - For a WEIGHTED graph, none of this generalizes directly. BFS's correctness depends entirely on every edge costing exactly one step; the moment edges have different costs, this becomes Dijkstra's algorithm territory (or 0-1 BFS specifically for
{0,1}-weighted edges), not a variant of plain BFS.
Implement BFS on an implicit graph (state space) where each state's neighbors are generated by a function produce_neighbors(state). Write find_shortest_sequence(start, goal, produce_neighbors) in Python to return the shortest move sequence. Discuss pruning strategies, heuristics, and how to guarantee shortest path (when allowed to prune). Suggest bidirectional search when applicable.
Sample Answer
Direct answer
An implicit graph never materializes its full node or edge set up front: neighbors are computed on demand by calling produce_neighbors(state), and breadth-first search (BFS) still applies unmodified, since BFS only ever needs "give me the neighbors of this node right now," never the whole graph at once. This is exactly what a state-space search (a puzzle, a game position, an abstract configuration space) needs, since materializing every reachable state ahead of time is often impossible or wasteful.
Structured elaboration
Why BFS still guarantees shortest path here. BFS's core guarantee, the first time a state is discovered it is at its true minimum distance, depends only on exploring states in non-decreasing distance order, never on knowing the graph's shape in advance. Calling produce_neighbors lazily, one node at a time, preserves this exactly: each call happens precisely when that node is dequeued, in the same layer-by-layer order BFS always uses.
Pruning strategies. A visited set is the baseline prune (never re-expand a state already discovered), but implicit graphs often support domain-specific pruning too: reject a neighbor immediately if it violates an invariant (an illegal board position, a state outside a known-safe region) before it is ever added to the queue, saving both the memory to store it and the future work of expanding it. Pruning by domain invariant must never prune a state that could still be on SOME shortest path, or the "shortest" guarantee breaks; a prune based purely on redundancy (already visited) is always safe, a prune based on heuristic judgment is not automatically safe unless proven admissible.
Heuristics. If a heuristic estimate of remaining distance to the goal is available, switching from plain BFS to A* (using the heuristic to prioritize which state to expand next via a priority queue instead of a FIFO queue) can dramatically reduce the number of states visited, at the cost of losing BFS's simplicity and requiring the heuristic to be admissible (never overestimate the true remaining distance) to keep the shortest-path guarantee.
Bidirectional search. When both start and goal are known in advance (not always true in state-space search, but common), growing frontiers from both ends and stopping when they meet bounds the search to roughly the square root of the single-direction node count for a typical branching factor, the same principle as bidirectional BFS on any explicit graph.
Worked example
from collections import deque
from typing import Callable, Iterable, List, Optional, TypeVar
State = TypeVar("State")
def find_shortest_sequence(start: State, goal: State,
produce_neighbors: Callable[[State], Iterable[State]]) -> Optional[List[State]]:
if start == goal:
return [start]
parent = {start: None}
q = deque([start])
while q:
s = q.popleft()
for nxt in produce_neighbors(s):
if nxt in parent:
continue
parent[nxt] = s
if nxt == goal:
path = [nxt]
cur = nxt
while parent[cur] is not None:
cur = parent[cur]
path.append(cur)
return list(reversed(path))
q.append(nxt)
return None
if __name__ == "__main__":
# Abstract 12-state space: from state s, neighbors are s+1, s-1, s+5 (mod 12).
# Deliberately not a literal grid or puzzle, to make the point that BFS
# does not care what a "state" actually represents.
N = 12
def produce_neighbors(state):
return [(state + 1) % N, (state - 1) % N, (state + 5) % N]
path = find_shortest_sequence(0, 7, produce_neighbors)
print("Shortest sequence 0 -> 7:", path)
print("Steps:", len(path) - 1 if path else None)
def is_valid(path, produce_neighbors):
return all(path[i+1] in set(produce_neighbors(path[i])) for i in range(len(path)-1))
print("Path uses only real transitions:", is_valid(path, produce_neighbors))
def full_bfs_dist(start, produce_neighbors):
dist = {start: 0}
q = deque([start])
while q:
u = q.popleft()
for v in produce_neighbors(u):
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist
ref = full_bfs_dist(0, produce_neighbors)
print("Matches independent full-BFS distance table:", ref[7] == len(path) - 1)
print("No path from a state that only transitions to itself:", find_shortest_sequence(100, 200, lambda s: [s]))
Output (actually executed with python3):
Shortest sequence 0 -> 7: [0, 1, 2, 7]
Steps: 3
Path uses only real transitions: True
Matches independent full-BFS distance table: True
No path from a state that only transitions to itself: None
The independent full_bfs_dist helper computes distances to every reachable state from scratch, without reusing the path-returning function's logic, and its distance to state 7 (3) matches len(path) - 1 exactly, confirming the lazily-called produce_neighbors version is genuinely finding a true shortest sequence, not just any sequence.
Complexity
Time O(N+E) where N is the number of reachable states and E is the number of transitions actually explored (both unknown in advance for a true implicit graph, unlike an explicit one where V and E are given). Space O(N) for parent and the queue. Each call to produce_neighbors is charged whatever it costs to compute (in the example above, O(1); in a real puzzle, it might be proportional to board size).
Edge cases
start == goal: returns[start]immediately, a zero-move sequence, without ever callingproduce_neighbors.- No path exists (as demonstrated by the self-loop-only state 100 in the worked example): the queue drains completely,
parentnever gains an entry forgoal, and the function returnsNone. produce_neighborsyielding a state already on the current path (a state with a transition back to itself, or a cycle in the state graph): handled the same as any other implicit-graph cycle, since theparentdict doubles as the visited set, a state already discovered is never re-enqueued.produce_neighborsraising an exception mid-search (a real risk if computing a state's neighbors can fail, for example an invalid board configuration): not handled by the implementation above, and worth flagging explicitly as something a production version would need to decide on: abort the whole search, or treat that state as having no valid neighbors and continue.
Trade-offs and pitfalls
- Common mistake: calling
produce_neighborsmore than once for the same state (for example, once to check if any neighbor is the goal, and again to actually enqueue them). Since neighbor generation can be expensive in a real state space, the implementation above calls it exactly once per dequeued state and processes each yielded neighbor as it arrives. - Common mistake: pruning by a heuristic that is not admissible (can overestimate true remaining distance), which silently breaks BFS's shortest-path guarantee; a state that gets pruned because it "looks unpromising" might still sit on the actual shortest path.
- Infinite or unbounded state spaces. Unlike a finite explicit graph, an implicit state space can be infinite (an unbounded counter, an open-ended configuration). Plain BFS on such a space either runs forever if
goalis unreachable, or needs an explicit depth cap or iterative-deepening strategy layered on top to guarantee termination even on a "no path exists" input. - When to reach for A instead.* If a genuinely admissible heuristic exists (an under-estimate of remaining distance that is cheap to compute), A* dominates plain BFS by visiting fewer states while preserving the same shortest-path guarantee; if no such heuristic is available or trustworthy, plain BFS remains the safe default.
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.
Given an undirected graph represented as an adjacency list, write a function to compute the number of connected components and return a list of components (each component is a list of nodes). Your implementation should handle isolated nodes correctly and run in O(V+E) time. Explain your choice of BFS vs DFS and space complexity.
Sample Answer
Direct answer
Compute connected components with a standard flood-fill: iterate over every node, and whenever you find one that has not been visited yet, run a breadth-first search (BFS) or depth-first search (DFS) from it, collecting every node it reaches into one component and marking all of them visited. Each node and each edge is touched a constant number of times across the whole run, so the total cost is O(V+E) regardless of how many components exist. BFS and DFS both achieve this bound; the choice between them is about auxiliary space and recursion behavior, not correctness or asymptotic speed.
Structured elaboration
Algorithm, using BFS to avoid Python's recursion-depth limit on deep or path-like components:
- Maintain a
visitedset and acomponentslist. - For every node
startin the graph (this loop is what correctly handles isolated nodes: a node with an empty neighbor list still gets its own singleton BFS run and becomes its own component):- If
startis already visited, skip it. - Otherwise, start a new BFS from
start, marking each node visited exactly once as it is discovered (not when it is dequeued), and append every node BFS reaches to a new component list.
- If
- Return the list of components.
Why mark visited at discovery, not at dequeue: if you wait to mark a node visited until you pop it from the queue, the same node can be pushed onto the queue multiple times by different neighbors before it is ever dequeued, which does not break correctness but does waste work and, in pathological dense graphs, can blow up the queue size well past O(V). Marking at discovery keeps each node enqueued at most once.
Complexity. Time: O(V+E), because the outer loop over all nodes is O(V), and across the ENTIRE run (not per component) every edge is examined exactly twice for an undirected graph represented as an adjacency list, once from each endpoint, giving O(E) total edge work. Space: O(V) for the visited set and the BFS queue in the worst case (a single component containing all nodes).
BFS vs DFS choice here: DFS (recursive) is more compact to write but risks a stack overflow on a graph with a long path-shaped component, since Python's default recursion limit is 1000; an iterative DFS with an explicit stack avoids that but is not meaningfully simpler than BFS once you write it iteratively. BFS with a deque avoids the recursion-depth risk entirely and is the safer default for a function that has to run correctly on arbitrary, potentially adversarial input graphs.
Worked example
from collections import deque
from typing import Dict, List
def connected_components(adj: Dict[int, List[int]]) -> List[List[int]]:
seen = set()
comps = []
for start in adj:
if start in seen:
continue
comp = []
q = deque([start])
seen.add(start)
while q:
u = q.popleft()
comp.append(u)
for v in adj[u]:
if v not in seen:
seen.add(v)
q.append(v)
comps.append(sorted(comp))
return comps
if __name__ == "__main__":
# 7 nodes: {0,1,2} triangle, {3,4} edge, {5} isolated, {6} isolated
adj = {0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4], 4: [3], 5: [], 6: []}
comps = connected_components(adj)
print("components:", comps)
print("count:", len(comps))
Output:
components: [[0, 1, 2], [3, 4], [5], [6]]
count: 4
This confirms both required properties: the isolated nodes 5 and 6 correctly appear as their own singleton components (they are never silently dropped by only iterating over edges), and the return shape is a list of component member-lists, not just a count.
Trade-offs and pitfalls
- Space complexity is O(V), not O(V+E), for the traversal itself: the visited set and queue hold at most V node entries total across the run. (The O(V+E) figure describes the input adjacency structure's size, not the extra space this algorithm allocates on top of it.)
- Common mistake: only iterating over edges to find components, which silently drops isolated nodes (nodes with no adjacency-list entries at all, or an empty entry) because they never appear as an edge endpoint. The
for start in adjouter loop over ALL nodes, not just edge endpoints, is what fixes this; if the adjacency map itself is only built from edges, isolated nodes must be seeded into it (with an empty neighbor list) before this function runs. - Common mistake: recomputing reachability from scratch inside the loop instead of sharing one growing
visitedset, which turns an O(V+E) algorithm into O(V⋅(V+E)) by redoing work for every already-visited node. - DFS's recursion-depth risk is real, not theoretical, for pipeline or production code accepting untrusted graph shapes: a component shaped like a long chain (a "path graph") recurses to a depth equal to its length, and Python's default limit of 1000 will raise a
RecursionErroron a chain of roughly that length or longer. BFS or an explicit-stack DFS avoids this entirely.
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.