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.
Implement topological sort for a DAG using Kahn's algorithm in Python. Function signature: def topological_sort(graph: Dict[int, List[int]]) -> Optional[List[int]]. Return a list representing one valid topological order or None if a cycle exists. Include a small example graph and explain how the algorithm detects cycles.
Sample Answer
Direct answer
Kahn's algorithm computes a topological order of a directed acyclic graph (DAG) by repeatedly removing vertices whose in-degree (count of incoming edges) is currently zero: track in-degree for every vertex, seed a queue with the zero-in-degree vertices, and each time one is popped and appended to the output, decrement its neighbors' in-degrees, enqueueing any that just hit zero. If fewer vertices end up in the output than exist in the graph, a cycle is blocking the rest from ever reaching in-degree zero, and the function returns None.
Structured elaboration
The implementation below assumes graph is a complete adjacency map: every vertex, including pure sinks with no outgoing edges, has an entry (possibly an empty list). This matters because in-degree needs to be initialized to 0 for every vertex up front, including ones that never appear as a source in an edge.
Worked example
from collections import deque
from typing import Dict, List, Optional
def topological_sort(graph: Dict[int, List[int]]) -> Optional[List[int]]:
# Kahn's algorithm. graph maps every node id (including sinks) to its
# list of out-neighbors. Returns one valid topological order, or None if
# the graph contains a cycle.
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] += 1
q = deque([u for u in graph if indegree[u] == 0])
order = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
q.append(v)
if len(order) != len(graph):
return None # some node's indegree never hit 0: a cycle is holding it back
return order
if __name__ == "__main__":
dag = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: []}
result = topological_sort(dict(dag))
print("DAG order:", result)
cyclic = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [1]} # 1 -> 3 -> 4 -> 1
result_cyclic = topological_sort(dict(cyclic))
print("Cyclic graph result:", result_cyclic)
def is_valid_topo(order, graph):
pos = {n: i for i, n in enumerate(order)}
return all(pos[u] < pos[v] for u in graph for v in graph[u])
print("DAG order is valid:", is_valid_topo(result, dag))
Output (actually executed with python3):
DAG order: [0, 1, 2, 3, 4]
Cyclic graph result: None
DAG order is valid: True
How cycle detection works. Every vertex on a cycle has at least one incoming edge from within that same cycle, so its in-degree can only reach zero if something outside the cycle first breaks the dependency, which never happens for a pure cycle. The example above adds edge 4 -> 1 to the acyclic graph, creating the cycle 1 -> 3 -> 4 -> 1. Tracing it: vertex 0 has in-degree 0 and is popped first, dropping vertex 2's in-degree to 0 (vertex 2 is not on the cycle); vertex 2 is popped next, but the one edge it contributes (2 -> 3) only drops vertex 3's in-degree from 2 to 1, not to 0, because 3 is still waiting on vertex 1, which is still waiting on vertex 4, which is still waiting on vertex 1. The queue empties with only [0, 2] ever output, two vertices short of the graph's five, and the length check correctly returns None instead of a partial, misleading order.
Complexity
Time O(V+E): every vertex is enqueued and dequeued exactly once, and every edge is inspected exactly once when decrementing its target's in-degree. Space O(V) for the in-degree map and the queue, on top of the O(V+E) already used to store the adjacency list itself.
Edge cases
- Empty graph:
graph = {}returns[]immediately, since the length check0 == 0passes trivially. - Self-loop (
graph = {0: [0]}): vertex 0's in-degree is 1 from the start (its own edge), so it never enters the queue, and the function correctly returnsNone, since a self-loop is a one-vertex cycle. - Disconnected components: each component's own zero-in-degree vertices seed the queue independently; the algorithm does not require a single connected structure, and the final order simply interleaves both components in whatever sequence the queue happens to drain them.
- Multiple valid orders: whenever two or more vertices are simultaneously in-degree zero, their relative order in the output depends on queue insertion order, which is not part of the contract of "a" valid topological order (any of them is correct).
Trade-offs and pitfalls
- Determinism. As written, this function's exact output can depend on Python's dict/list iteration order for
graph, which is consistent for identical input but not necessarily portable across a re-implementation in another language. If a caller needs a reproducible, cross-implementation-stable order (for example, for a golden test fixture or an audit log), swap the FIFOdequefor a min-heap keyed on vertex id, which forces the lexicographically smallest valid order every time; that variant is common enough to be its own interview question. - Deployment-ordering framing: the same function, with vertices renamed to services and edges to "must deploy before," is exactly a safe deployment-order computation; the only change needed is deciding what to do with the
Nonecase in production (reject the deployment plan and surface the offending services, rather than silently deploying a partial, broken order). - Machine learning (ML) use-case framing: the same function orders a feature-store's dependency graph so a derived feature is only computed after every feature it reads from;
Nonethere means a circular feature definition, a configuration bug worth failing loudly on rather than silently truncating. - Common mistake: initializing
indegreeonly from vertices that appear as an edge's source, which silently omits pure-sink vertices and can undercount, or skip, legitimate zero-in-degree starting points; the dict comprehension{u: 0 for u in graph}above avoids this by seeding every vertex the caller declared, not just ones seen as an edge source. - Common mistake: mutating the caller's
graphdict in place while consuming it (for example, popping neighbor lists as they are processed); the implementation above only readsgraph, never writes to it, so the caller's structure is safe to reuse afterward.
Write a Python function that detects whether an undirected graph (adjacency list Dict[int, List[int]]) contains any cycle. The function should return True if a cycle exists and False otherwise. Explain why you must track the parent node during DFS to avoid false-positive detection from immediate back-edges. Ensure O(|V|+|E|) time.
Sample Answer
Direct answer
In an undirected graph, DFS with a tracked parent argument detects a cycle by treating an edge to an already-visited node as a cycle, EXCEPT when that already-visited node is the immediate parent, since every undirected edge is stored twice (once in each endpoint's adjacency list), so walking straight back along the edge you just arrived on would otherwise look identical to a genuine cycle. Passing the parent explicitly and skipping exactly that one edge is what makes the check correct.
Structured elaboration
Why the parent check exists at all. An undirected edge (u,v) is represented as v∈graph[u] AND u∈graph[v], both directions stored. A DFS that goes from u to v will, when examining v's neighbors, immediately see u again, the edge it just came from. Without a parent check, this looks exactly like discovering an already-visited node, indistinguishable from a real cycle, even on a simple two-node graph with a single edge and no cycle at all. Recording the parent and explicitly skipping the edge back to it removes this false signal while leaving every genuine cycle (an edge into a visited node that is NOT the immediate parent) correctly detected.
Worked example
from typing import Dict, List
def has_cycle(graph: Dict[int, List[int]]) -> bool:
visited = set()
def dfs(u: int, parent: int) -> bool:
visited.add(u)
for v in graph.get(u, []):
if v == parent:
continue # the edge back to where we came from, not a cycle
if v in visited:
return True # a back-edge to an already-visited, non-parent node: a cycle
if dfs(v, u):
return True
return False
for node in graph:
if node not in visited:
if dfs(node, -1):
return True
return False
if __name__ == "__main__":
tree = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1]} # a genuine tree, no cycle
print("tree (no cycle):", has_cycle(tree))
triangle = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
print("triangle (cycle):", has_cycle(triangle))
disconnected_with_cycle = {0: [1], 1: [0], 2: [3, 4], 3: [2, 4], 4: [2, 3]}
print("disconnected, cycle only in 2nd component:", has_cycle(disconnected_with_cycle))
isolated = {0: [], 1: [], 2: []}
print("all isolated nodes:", has_cycle(isolated))
self_loop = {0: [0]}
print("self-loop:", has_cycle(self_loop))
def edges_from_adj(adj):
seen = set()
edges = []
for u in adj:
for v in adj[u]:
if (v, u) not in seen:
edges.append((u, v))
seen.add((u, v))
return edges
def brute_force_has_cycle(adj):
# Independent ground truth via plain union-find (correct here since
# this check is over UNDIRECTED edges, where union-find is valid).
nodes = list(adj.keys())
idx = {n: i for i, n in enumerate(nodes)}
parent = list(range(len(nodes)))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for u, v in edges_from_adj(adj):
ru, rv = find(idx[u]), find(idx[v])
if ru == rv:
return True
parent[ru] = rv
return False
for name, g in [("tree", tree), ("triangle", triangle), ("disconnected", disconnected_with_cycle), ("isolated", isolated)]:
print(f"cross-check {name}:", has_cycle(g) == brute_force_has_cycle(g))
Output (actually executed with python3):
tree (no cycle): False
triangle (cycle): True
disconnected, cycle only in 2nd component: True
all isolated nodes: False
self-loop: True
cross-check tree: True
cross-check triangle: True
cross-check disconnected: True
cross-check isolated: True
Every DFS-with-parent result is cross-checked against a completely independently implemented union-find (correct for THIS undirected-only use case, unlike the directed case where union-find is unsound). The self_loop case (0: [0]) is correctly reported True: when DFS at node 0 examines its own self-loop edge, the neighbor is 0 itself, which is already in visited (added at the start of the call) and is NOT equal to parent (which is −1 for the root call), so it correctly falls through to the cycle-detected branch.
Complexity
Time O(∣V∣+∣E∣): each vertex is visited at most once (guarded by visited), and each edge is examined at most twice total (once from each endpoint), a constant factor that does not change the asymptotic bound. Space O(∣V∣) for visited and the recursion stack.
Edge cases
- Disconnected graph: the outer loop restarts DFS from every unvisited node, so a cycle in any component is found regardless of which component happens to be explored first.
- Isolated nodes (no edges at all): trivially no cycle, handled without any special-casing since the inner loop over
graph.get(u, [])simply does nothing. - Self-loop (
v == u): correctly detected as a cycle, as traced above; note thatv == uis NOT the same check asv == parent, so a self-loop is never accidentally treated as "the edge back to my parent" even on the very first call whereparentstarts at a sentinel value. - Parallel edges between the same pair (the same undirected edge listed twice): would be misreported as a cycle by this implementation, since the second occurrence of the neighbor is not equal to
parenton the SECOND time it is examined even though it is the same physical edge; a graph representation that can contain true parallel edges needs an explicit edge-id (not just a node-id) comparison to skip correctly, which this simple adjacency-list version does not attempt to solve.
Trade-offs and pitfalls
- Common mistake: omitting the parent parameter entirely and using a plain "is this neighbor visited" check, which reports every single edge in an undirected graph as a cycle, since the edge back to the immediate parent always looks like a revisit.
- Common mistake: comparing against a set or list of ALL ancestors instead of just the immediate parent. For an undirected graph this is unnecessary extra work, since only the single edge just traversed needs to be excluded, not the whole ancestor chain, that distinction (immediate parent only, versus the full ancestor set) is precisely what separates undirected cycle detection from the analogous directed case, where the full "on the current path" (gray/inStack) set genuinely is needed.
- Why this technique is undirected-specific. The parent-skip trick exists purely because undirected edges are stored bidirectionally; a directed graph never has this "walking back along the same edge looks like a revisit" problem in the first place, since a directed edge u→v has no automatic reverse entry, which is why directed cycle detection needs the gray/inStack (full active-path) mechanism instead of a simple single-parent exclusion.
Implement a BFS-based bipartiteness check in Python. Function is_bipartite(graph) should return True/False and a 2-coloring if bipartite. Graph may be disconnected. Explain why BFS/DFS coloring works and the complexity.
Sample Answer
Direct answer
is_bipartite(graph) runs a BFS two-coloring pass from every not-yet-colored node (handling disconnected input), assigning each newly discovered node the opposite color of the node that discovered it, and returns False the instant an edge connects two nodes already colored the same. If the BFS completes with no such conflict, the graph is bipartite and the accumulated coloring is a valid 2-coloring, returned alongside True.
Structured elaboration
Why BFS coloring works. In a bipartite graph, every edge must connect the two groups, never two nodes within the same group, so any correct 2-coloring must alternate colors across every edge. BFS naturally colors nodes by their distance parity from the component's start node (all nodes at even distance get one color, all nodes at odd distance get the other), and this is EXACTLY a valid bipartition whenever one exists, because two nodes connected by a direct edge always differ in BFS distance by exactly 1 in a correctly-behaving coloring, guaranteeing opposite colors. A conflict (an edge whose endpoints end up the same color) can only arise when the graph structure forces two nodes at the same distance-parity from the start to also be directly connected, which happens precisely when an odd-length cycle exists.
Handling disconnection. Nodes with no path to the component the algorithm happened to start with have no BFS-derived color yet; the outer loop over every node index ensures each such component gets its OWN independent coloring pass, since disconnected components impose no constraint on each other's color choice.
Complexity. O(V+E): every node is colored exactly once, and every edge is examined at most twice (once from each endpoint) across the whole run, the same bound as any BFS/DFS traversal over the full graph.
Worked example
from collections import deque
from typing import List, Optional, Tuple
def is_bipartite(graph: List[List[int]]) -> Tuple[bool, Optional[List[int]]]:
n = len(graph)
color = [-1] * n
for start in range(n):
if color[start] != -1:
continue
color[start] = 0
q = deque([start])
while q:
u = q.popleft()
for v in graph[u]:
if color[v] == -1:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False, None
return True, color
if __name__ == "__main__":
# Case 1: bipartite (square, 0-1-2-3-0)
graph1 = [[1, 3], [0, 2], [1, 3], [2, 0]]
ok1, coloring1 = is_bipartite(graph1)
print("graph1:", graph1)
print("is_bipartite:", ok1, "coloring:", coloring1)
# Case 2: NOT bipartite (triangle, 0-1-2-0)
graph2 = [[1, 2], [0, 2], [0, 1]]
ok2, coloring2 = is_bipartite(graph2)
print("\ngraph2:", graph2)
print("is_bipartite:", ok2, "coloring:", coloring2)
# Case 3: disconnected, mix of a bipartite path and an isolated node
graph3 = [[1], [0, 2], [1], []]
ok3, coloring3 = is_bipartite(graph3)
print("\ngraph3:", graph3)
print("is_bipartite:", ok3, "coloring:", coloring3)
Output:
graph1: [[1, 3], [0, 2], [1, 3], [2, 0]]
is_bipartite: True coloring: [0, 1, 0, 1]
graph2: [[1, 2], [0, 2], [0, 1]]
is_bipartite: False coloring: None
graph3: [[1], [0, 2], [1], []]
is_bipartite: True coloring: [0, 1, 0, 0]
Graph 1 (a 4-node cycle) two-colors cleanly ([0,1,0,1], alternating perfectly around the cycle). Graph 2 (a 3-node cycle, a triangle, the smallest possible odd cycle) fails, correctly returning None for the coloring rather than a partial or misleading result. Graph 3 (a disconnected graph: a 3-node bipartite path 0-1-2 plus an isolated node 3) succeeds, and node 3, having no edges, keeps whatever color the outer loop happens to assign it (color 0 here, since it starts its own trivial single-node component); an isolated node can never itself cause a conflict, since it has no edges to check.
Trade-offs and pitfalls
- Common mistake: returning
Falsebut still returning a PARTIAL, invalid coloring array instead ofNone(or otherwise clearly signaling invalidity). A caller that does not carefully check the boolean first could mistake a partial, contradiction-containing coloring for a genuine 2-coloring; returningNonefor the coloring on theFalsepath makes this class of bug impossible rather than merely unlikely. - Common mistake: only starting BFS once, from node 0. On a graph with disconnected components, this leaves later components entirely uncolored and unchecked; the fix is looping the outer
for start in range(n)over every node, which this implementation does correctly. - An isolated node is trivially bipartite on its own (it has no edges to violate the bipartition condition), and this implementation handles it for free: it becomes its own singleton component, gets colored, and the while-loop body (which only runs on an edge) never executes for it.
- This early-returns on the FIRST conflict found, which is efficient (no wasted work continuing to color a graph already known non-bipartite) but means the specific coloring state at the moment of the return is an implementation artifact of traversal order, not something a caller should read any meaning into beyond "a conflict exists somewhere."
While on-call you detect that a recent change introduced a circular dependency causing a failed rollout. Describe a practical approach to detect such cycles automatically in CI before merges are accepted: which graph algorithm to run, how to construct the dependency graph from manifests/configs, where to integrate the check, and how to scale it for large repos and many services.
Sample Answer
Direct answer
Detect circular service dependencies automatically by building a directed graph from the same manifests that already declare "A depends on B" (Kubernetes manifests, Helm charts, Terraform modules, or an internal service registry), running a linear-time cycle-detection pass (depth-first search, DFS, with the standard white/gray/black coloring, or Tarjan's strongly connected components (SCC) algorithm if a richer diagnostic is wanted) over that graph, and blocking the merge in continuous integration (CI) the moment a cycle is found, before the change that introduces it ever reaches a running environment.
Structured elaboration
Which algorithm to run. A plain DFS-based cycle check (white/gray/black coloring, detecting a back edge into a still-gray node) is sufficient to answer yes/no and, with parent tracking, to reconstruct the specific offending cycle; it runs in O(V+E) and is the simplest correct tool for the job. Tarjan's SCC algorithm, also O(V+E), is a genuinely richer diagnostic: it partitions the ENTIRE graph into strongly connected components in one pass, so if multiple independent cycles exist simultaneously (plausible in a large, poorly-audited dependency graph), Tarjan's reports every one of them at once, each as its own component, rather than requiring the simple DFS check to be re-run repeatedly after each cycle is manually removed. For a one-shot pre-merge gate answering "is THIS specific change introducing a cycle," plain DFS is enough; for a periodic full-repository audit surfacing every existing tangle for cleanup, Tarjan's SCC output is more actionable.
Constructing the dependency graph from manifests. The graph's nodes are services (or components, or modules, whatever the deployable unit is); edges are extracted by parsing each manifest type for its own dependency-declaration convention:
- Kubernetes manifests: a
Deploymentreferencing another service'sServiceendpoint (via an environment variable, aConfigMap/Secretreference, or aninitContainerthat waits on another service) is a dependency edge. - Helm charts: a chart's
values.yamlorChart.yamlreferencing a subchart or another chart's release is a dependency edge. - Terraform: an explicit
depends_onblock, or an implicit dependency inferred from one module referencing another module's output, is a dependency edge. - Application-level manifests: an explicit
services: [auth, db]-style declared dependency list, where the application itself states what it needs running first, is the most direct and least ambiguous source, when it exists.
Every source normalizes to the same output shape: a plain edge list (or adjacency map) keyed by a canonical service identifier (cluster + namespace + service name, to avoid two same-named services in different namespaces being conflated into one node), which the cycle-detection algorithm then consumes uniformly regardless of which manifest type originally declared the edge.
Where to integrate the check. As a mandatory, blocking step in the pull-request (PR) merge pipeline: parse every changed manifest in the PR (plus enough of the surrounding, UNCHANGED graph to know what those changed pieces connect to), run cycle detection, and fail the CI check with the SPECIFIC cycle's node path if one is found, before the PR is mergeable at all. This is deliberately a pre-merge gate, not a post-deploy alarm, because the whole point is preventing a circular dependency from ever reaching a state where it could cause a deployment-ordering deadlock (an on-call engineer discovering two services each waiting on the other to become healthy first). A secondary, non-blocking NIGHTLY full-repository scan is worth running in addition, specifically to catch a cycle introduced indirectly (two independently-merged, individually-cycle-free PRs whose combination creates a cycle neither PR's own incremental check would have seen in isolation, since each PR's incremental check only sees its own diff against the graph as it existed at merge time).
Scaling for large repos and many services. Three concrete techniques, layered:
- Incremental, diff-scoped checking on the PR path. Re-parsing and re-checking the ENTIRE dependency graph on every PR does not scale as the service count grows into the thousands; instead, parse only the changed manifests, resolve which existing nodes their new or modified edges touch, and run cycle detection on the union of "changed nodes plus their existing neighbors," which is sufficient to catch any NEW cycle the PR could introduce, since a cycle must pass through at least one changed edge to be new.
- Cache the parsed graph, invalidated by manifest changes. Rebuilding the whole graph from every manifest in the repository on every check is wasteful when the vast majority of manifests are unchanged between runs; a persisted graph snapshot, updated incrementally as manifests change (keyed by manifest content hash, so an unchanged file is never re-parsed), keeps the common-case check fast regardless of total repository size.
- Run the check as a small, containerized job reading a repository-metadata export, not as a step that re-clones and re-parses the entire monorepo from scratch inside the CI runner; separating "extract the manifest snapshot" from "run graph analysis on it" lets the analysis step scale independently and be reused by both the PR-scoped fast path and the nightly full-repository scan.
Worked example
A PR modifies service-payments's manifest to add a dependency on service-notifications. The incremental check resolves the existing graph neighborhood: service-notifications already depends on service-audit, which already depends on service-payments (declared in a completely different, unrelated PR merged months earlier). Adding the new edge service-payments -> service-notifications closes the cycle service-payments -> service-notifications -> service-audit -> service-payments. Because the check resolves not just the changed manifest but its existing neighbors, it catches this even though neither service-notifications's nor service-audit's manifests were touched by this PR at all; a check that only validated the PR's own changed files in isolation, without pulling in their existing graph context, would have missed this cycle entirely.
Trade-offs and pitfalls
- Common mistake: checking only the files changed in the PR without resolving what they connect to in the EXISTING graph, which misses exactly the cross-PR cycle shown in the worked example above; the check's scope needs to be "changed edges plus their existing graph neighborhood," not merely "changed files."
- Common mistake: running the check only as a nightly batch job and not as a blocking PR gate. A nightly-only check still lets a cycle merge and potentially deploy before the next scheduled scan catches it, turning a preventable, cheap-to-block-at-merge-time problem into a reactive incident.
- False negatives from incomplete manifest parsing. If the extraction logic misses a real dependency-declaration convention (a newer Helm pattern, a nonstandard annotation used by one team), the graph is silently incomplete, and cycle detection cannot catch a cycle formed through an edge it never saw. Treating the extraction step's coverage itself as something to monitor (what fraction of known dependency-declaration patterns does the parser recognize, and is that fraction tracked over time) is a real, ongoing maintenance cost, not a one-time build.
- Reporting quality matters as much as detection. A CI failure that says "cycle detected" with no further detail sends an engineer hunting through possibly dozens of services; surfacing the SPECIFIC cycle path (as DFS with parent tracking, or Tarjan's SCC membership, both directly support) turns a vague failure into an actionable one, and should be treated as a hard requirement of the check, not a nice-to-have.
- Human-friendly output in the PR itself (an inline comment on the specific manifest line that introduced the offending edge, via the CI platform's checks/comments API) meaningfully shortens the time to fix versus a failure that only points at a build log an engineer has to go dig through separately.
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.