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.
Given a directed acyclic graph (DAG) representing tasks with durations and precedence constraints, design an algorithm to compute the earliest completion time for each task and the overall project completion time. Explain how topological ordering and the critical path method are combined and how to modify the algorithm when resources are constrained (limited parallel workers).
Sample Answer
Direct answer
Compute each task's earliest start and earliest finish time with a single forward pass over a topological ordering of the dependency DAG: a task's earliest start is the maximum earliest-finish among all its direct predecessors (0 if it has none), and its earliest finish is its earliest start plus its own duration. The overall project completion time is the maximum earliest-finish across every task, and the critical path (the sequence of tasks that directly determines that completion time, with zero slack) is the longest path through the DAG when edges are weighted by task duration; this is exactly the classical critical path method (CPM), computed as a longest-path-in-a-DAG problem using topological order in place of Dijkstra/Bellman-Ford (neither of which is needed, since a DAG's topological order alone is sufficient to relax every edge exactly once in a correct dependency order).
Structured elaboration
Why topological order is sufficient (no shortest/longest-path algorithm needed). A task's earliest finish only depends on its predecessors' earliest finish times, which must already be known before that task can be processed. A topological order guarantees every predecessor of a task appears before it in the processing sequence, so a single forward pass, processing tasks in topological order and updating each successor's earliest-start as soon as a predecessor finishes, correctly computes every earliest-finish time in one O(V+E) pass, with no need for a priority queue or repeated relaxation the way Dijkstra or Bellman-Ford would require.
Algorithm (Kahn's-algorithm-style, computing earliest-finish as tasks are dequeued):
- Compute in-degree for every task; task with in-degree 0 have
earliest_start = 0. - Process tasks via a queue seeded with all in-degree-0 tasks (standard Kahn's algorithm). When a task
uis dequeued:earliest_finish[u] = earliest_start[u] + duration[u]. For every successorvofu:earliest_start[v] = max(earliest_start[v], earliest_finish[u]), decrementv's in-degree, and enqueuevonce its in-degree reaches 0. - The project completion time is
max(earliest_finish.values())across all tasks.
Modifying for resource-constrained scheduling (limited parallel workers). The unconstrained calculation above implicitly assumes UNLIMITED parallelism, every task with satisfied dependencies can start immediately. With only k workers, tasks whose dependencies are satisfied but who cannot get a free worker must WAIT even though the dependency graph alone would allow them to start, which turns this from a pure graph problem into resource-constrained project scheduling (RCPSP), a materially harder problem: RCPSP is NP-hard in general, unlike the polynomial-time unconstrained CPM calculation. A common practical approach is a priority-based simulation: at every point in simulated time, among all tasks whose dependencies are satisfied and are not yet running, greedily assign available workers by some priority rule (commonly least-slack-first, prioritizing tasks on or nearest to the critical path, since delaying THOSE tasks directly delays the project, while tasks with slack can absorb some worker-availability delay without affecting the overall completion time).
Worked example
from collections import deque
from typing import Dict, List
def earliest_completion(n: int, adj: Dict[int, List[int]], duration: Dict[int, int]):
indeg = {u: 0 for u in range(n)}
for u in adj:
for v in adj[u]:
indeg[v] += 1
q = deque([u for u in range(n) if indeg[u] == 0])
topo = []
earliest_start = {u: 0 for u in range(n)}
earliest_finish = {}
while q:
u = q.popleft()
topo.append(u)
earliest_finish[u] = earliest_start[u] + duration[u]
for v in adj.get(u, []):
earliest_start[v] = max(earliest_start[v], earliest_finish[u])
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
if len(topo) != n:
raise ValueError("graph has a cycle; no valid topological order")
return earliest_finish, max(earliest_finish.values()), topo
if __name__ == "__main__":
# 6 tasks (0..5): 0=build(3h) -> 1=docs(1h), 2=test(2h)
# 1=docs -> 3=review(2h); 2=test -> 3=review, 4=package(1h)
# 3=review -> 5=release(1h); 4=package -> 5=release
n = 6
duration = {0: 3, 1: 1, 2: 2, 3: 2, 4: 1, 5: 1}
adj = {0: [1, 2], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
finish, total, topo = earliest_completion(n, adj, duration)
print("topological order:", topo)
print("earliest finish times:", finish)
print("project completion time:", total)
serial_total = sum(duration[u] for u in topo)
print("fully-serial (1 worker) total:", serial_total)
Output:
topological order: [0, 1, 2, 3, 4, 5]
earliest finish times: {0: 3, 1: 4, 2: 5, 3: 7, 4: 6, 5: 8}
project completion time: 8
fully-serial (1 worker) total: 10
Hand trace confirms the algorithm: start(0)=0, finish(0)=3. start(1)=finish(0)=3, finish(1)=4. start(2)=finish(0)=3, finish(2)=5. start(3)=max(finish(1)=4, finish(2)=5)=5, finish(3)=7. start(4)=finish(2)=5, finish(4)=6. start(5)=max(finish(3)=7, finish(4)=6)=7, finish(5)=8. The critical path is 0-2-3-5 (durations 3+2+2+1=8), the longest chain of dependent tasks, exactly matching the computed project completion time of 8. With unlimited parallelism the project finishes in 8 hours; with only 1 worker (fully serial, everything runs one after another in ANY valid topological order), it takes the sum of all durations, 10 hours, a useful sanity bound: the true resource-constrained answer for any worker count between 1 and unlimited must fall between 8 (the critical path lower bound, unbeatable no matter how many workers) and 10 (the fully-serial upper bound) hours.
Trade-offs and pitfalls
- Common mistake: computing earliest-start/earliest-finish in an order that is topologically valid for the WRONG direction, or accidentally using arrival order instead of a true topological order; if any predecessor is processed after one of its successors, that successor's earliest-start would be computed using a stale (too-small) predecessor finish time, silently understating the true completion time.
- The unconstrained calculation (k=∞ workers) is a LOWER BOUND, never the true answer once a worker limit is introduced; a design that reports the unconstrained critical-path length as "the" completion time when workers are actually limited is reporting an optimistic, achievable-only-under-infinite-parallelism number, not the real constrained schedule.
- RCPSP (resource-constrained scheduling) is NP-hard, so an exact optimal schedule for large task counts under a worker limit is not efficiently computable in general; production systems use heuristics (least-slack-first, critical-path-first) that are good in practice but not provably optimal, a trade-off worth naming explicitly rather than implying a limited-worker schedule can always be computed exactly and efficiently.
- The fully-serial bound (sum of all durations) is only a valid upper bound when there is exactly 1 worker; with
k > 1butk < infinity, the achievable completion time lies somewhere between the critical-path lower bound and the fully-serial upper bound, and where exactly depends on the specific priority heuristic used and the DAG's branching structure, not on a simple closed-form formula.
Given a grid of '1's (land) and '0's (water), implement a Python function def num_islands(grid: List[List[str]]) -> int that counts the number of islands (connected components of 1s) using DFS or BFS. Include handling of edge cases such as empty grid and non-rectangular inputs. Discuss in-place marking vs using a visited matrix.
Sample Answer
Direct answer
A grid of land ('1') and water ('0') cells is an implicit graph where each land cell is a node connected to its up-to-four orthogonal land neighbors; counting islands is counting connected components. Scan every cell in row-major order, and each time an unvisited '1' is found, that is a brand-new island: run depth-first search (DFS) or breadth-first search (BFS) from it to mark every reachable land cell as visited, so the outer scan never counts the same island twice.
Structured elaboration
In-place marking versus a visited set. Flipping a visited land cell from '1' to '0' directly in the grid is the simplest way to mark it: no extra memory beyond the traversal's own stack or queue, but it destroys the caller's input, which is unacceptable if the grid needs to be reused or read again afterward. A separate visited boolean matrix (or a set of coordinates) avoids mutating the input at the cost of O(R×C) extra memory. The choice is a straightforward trade: mutate for memory efficiency when the caller has explicitly handed over ownership of the grid, use a visited structure otherwise.
Handling non-rectangular (jagged) input. A grid is not guaranteed to have every row the same length; bounds-checking a candidate neighbor must check against THAT row's own length (c < len(grid[r])), not a single global column count, or a jagged grid can silently index out of bounds on a shorter row.
Worked example
from typing import List
def num_islands(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows = len(grid)
def in_bounds(r, c):
return 0 <= r < rows and 0 <= c < len(grid[r])
islands = 0
for r in range(rows):
for c in range(len(grid[r])):
if grid[r][c] == '1':
islands += 1
stack = [(r, c)]
grid[r][c] = '0' # mark on discovery, in place
while stack:
x, y = stack.pop()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if in_bounds(nx, ny) and grid[nx][ny] == '1':
grid[nx][ny] = '0'
stack.append((nx, ny))
return islands
if __name__ == "__main__":
grid1 = [
list("11000"),
list("11000"),
list("00100"),
list("00011"),
]
print("grid1 islands:", num_islands([row[:] for row in grid1]))
print("empty grid:", num_islands([]))
jagged = [list("10"), list("111"), list("0")]
print("jagged grid islands:", num_islands([row[:] for row in jagged]))
all_water = [list("000"), list("000")]
print("all water:", num_islands([row[:] for row in all_water]))
def num_islands_bfs_reference(grid):
from collections import deque
if not grid or not grid[0]:
return 0
rows = len(grid)
visited = [[False] * len(row) for row in grid]
count = 0
for r in range(rows):
for c in range(len(grid[r])):
if grid[r][c] == '1' and not visited[r][c]:
count += 1
q = deque([(r, c)])
visited[r][c] = True
while q:
x, y = q.popleft()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < len(grid[nx]) and grid[nx][ny] == '1' and not visited[nx][ny]:
visited[nx][ny] = True
q.append((nx, ny))
return count
ref = num_islands_bfs_reference([row[:] for row in grid1])
print("Matches independent, non-mutating BFS reference:", ref == num_islands([row[:] for row in grid1]))
Output (actually executed with python3):
grid1 islands: 3
empty grid: 0
jagged grid islands: 1
all water: 0
Matches independent, non-mutating BFS reference: True
grid1 has three islands by hand-count: the 2x2 block in the top-left, the single cell at (2,2), and the two-cell block at (3,3)-(3,4). The jagged grid ["10","111","0"] has one island, since (0,0) connects vertically to (1,0), which connects horizontally to (1,1) and (1,2), all four cells joined into one component despite the rows having different lengths.
Complexity
Time O(R×C): the outer double loop visits every cell once, and the inner DFS/BFS, across the entire run, visits every land cell exactly once (each is marked immediately on discovery, never re-pushed). Space O(R×C) worst case for the traversal stack (a grid that is entirely one giant island) in the in-place version, or O(R×C) for the visited matrix plus the stack in the non-mutating version.
Edge cases
- Empty grid, or a grid whose first row is empty:
not grid or not grid[0]catches both and returns 0. - Non-rectangular (jagged) rows: handled by checking each candidate neighbor's bound against that specific row's own length, not a shared column count, as shown above.
- All water: the outer loop never finds a '1', returns 0 without ever starting a traversal.
- A single-cell island, or the entire grid being one connected island: both fall out naturally from the same code path with no special-casing.
- Diagonal adjacency: not counted by this implementation (only the four orthogonal directions), matching the standard problem definition; if diagonal adjacency were required, adding the four diagonal offsets to the direction list is the only change needed, and doing so can only merge islands, never split them, so the count can only decrease or stay the same relative to orthogonal-only adjacency.
Trade-offs and pitfalls
- Recursion depth at scale. A naive recursive DFS on a very large, single-island grid (for example 10,000 x 10,000, all land) recurses as deep as the island's longest simple path, which can exceed a language's default recursion limit; the iterative, explicit-stack version above sidesteps this entirely, which is why it is written iteratively rather than as a simpler-looking recursive function.
- Common mistake: checking
visited(or flipping to '0') only when a cell is POPPED from the stack rather than when it is first discovered and PUSHED. This lets the same cell be pushed multiple times by different neighbors before any of those pushes gets processed, wasting work and, in pathological cases, inflating the stack far beyond the actual number of distinct cells. - Common mistake: using a single shared column-count bound check on a grid that is not actually rectangular, which either throws an index error on a shorter row or, worse, silently reads stale data from a previous row's memory layout depending on the language and data structure.
- Diagonal-connectivity as a difficulty-bump variant. Making 4-direction versus 8-direction connectivity a runtime parameter (rather than hardcoded) is a natural follow-up: the algorithm's shape does not change, only the
directionslist does, but it is worth naming explicitly since some interviewers use it specifically to see whether a candidate treats "island" as a fixed rule or a configurable one.
In reinforcement learning, the environment's state-space can be represented as a directed graph. Discuss how choosing search strategies like DFS or BFS (and their variants) affects policy search, exploration efficiency, and safety. Propose heuristics (depth limits, iterative deepening, A*/heuristic-guided search) for large or infinite state spaces and mention when each is appropriate.
Sample Answer
Direct answer
Viewing a reinforcement learning (RL) environment as a directed graph (nodes are states, edges are actions/transitions) makes the search-strategy choice concrete: breadth-first search (BFS) explores by distance from the start state, favoring broad early coverage and finding shallow solutions fast; depth-first search (DFS) commits to long trajectories quickly, favoring deep, sparse discoveries at the cost of potentially wasting exploration budget on unpromising branches. Neither is "better" in the abstract; the right choice depends on whether the reward signal is shallow or deep, how large the branching factor is, and how much exploring a bad long trajectory actually costs.
Structured elaboration
How the choice affects policy search and exploration efficiency. BFS-flavored exploration (explicit BFS, or breadth-biased methods like prioritized sweeping that favor shallow, frequently-revisited states) gives even, early coverage across nearby states, which helps a policy learn a reasonable baseline behavior everywhere before specializing, but it pays for that coverage with high memory (the frontier can grow exponentially with branching factor) and can be slow to discover a reward that only appears after a long, specific sequence of actions. DFS-flavored exploration (explicit DFS, or depth-biased methods like plain trajectory rollouts that commit to one action sequence to completion before backtracking) is far more memory-efficient (only the current path needs to be held) and can stumble onto a deep, sparse reward faster by sheer commitment to depth, but it risks spending most of its exploration budget on one unpromising branch while leaving large parts of the state space completely unvisited, which shows up as high-variance, biased policy estimates.
Safety implications. The two strategies fail differently. A DFS-biased agent that commits deeply into an untested trajectory before backing off can walk directly into a hazardous or irreversible state (a physical robot damaging itself, a financial agent making a large bad trade) before any safety check has a chance to intervene, since depth-first commitment means the agent is many steps deep before it "reconsiders." A BFS-biased agent's shallow, even exploration is comparatively safer by construction, since it never commits far from a known-good region without first characterizing the nearby states, but this safety comes at the direct cost of the memory and coverage trade-offs above. Constraining search explicitly (shielding: rejecting actions that lead to states flagged unsafe by a domain model, before they are ever taken) is a strategy-independent safety layer that should sit on top of either choice, not a substitute for choosing the less risky one.
Heuristics for large or infinite state spaces.
- Depth limits. Cap how deep a DFS-style rollout is allowed to go before backtracking, bounding worst-case memory and worst-case exposure to an unexplored, potentially hazardous deep state. Appropriate when the reward is known or suspected to be shallow, or when deep exploration without a check-in point is itself the risk to avoid.
- Iterative deepening. Run depth-limited DFS repeatedly with an increasing depth cap (1, then 2, then 3, ...), which gets DFS's low memory footprint while still guaranteeing BFS's property of finding the shallowest solution first, at the cost of re-exploring shallow states on every iteration. Appropriate when memory is the binding constraint but the shallow-solution guarantee still matters (for example, safety-critical settings where confirming no shallow, cheap solution exists is required before committing to deeper, riskier exploration).
- A or heuristic-guided search.* When a value estimate or model can score how promising a state is (a learned value function, a domain heuristic), prioritizing expansion toward high-value states over blind BFS or DFS focuses the exploration budget where it is likely to pay off, provided the heuristic does not systematically mislead the agent away from a true optimum. Appropriate once a reasonably reliable value estimate exists (often after some initial BFS- or DFS-style exploration has bootstrapped one); using it too early, before the value estimate is trustworthy, risks the agent confidently exploring the wrong region.
Worked example
A sparse-reward navigation task: an agent in a large grid-like environment gets a reward only upon reaching one specific distant cell, with no intermediate signal.
Pure BFS-style exploration systematically covers nearby cells first and will eventually reach the distant goal, but the number of states visited before reaching a reward that is d steps away grows like the branching factor raised to d, which becomes intractable for large d; the agent essentially never gets useful gradient signal until BFS's frontier happens to reach the goal region. Pure DFS-style exploration (a single long rollout committing to one direction) can reach the goal in O(d) steps if it happens to commit in the right general direction, but with no guidance, it is equally likely to commit in the wrong direction and waste the entire episode. A depth-limited DFS with iterative deepening bounds the worst case (never wanders further than the current depth cap without backtracking) while still eventually trying the shallow options first, and adding a coarse heuristic (Euclidean or graph distance toward the last-known reward direction, if any signal exists) to bias which direction to commit to first turns "equally likely to go the wrong way" into "much more likely to go the right way," which is exactly the justification for moving to heuristic-guided search once a rough heuristic becomes available.
Trade-offs and pitfalls
- Common mistake: treating the search-strategy choice as separate from the safety mechanism. Depth limits and shielding solve different problems (bounding worst-case exposure to depth vs. rejecting specific unsafe actions); a system that only uses one is not fully protected against the other's failure mode.
- Common mistake: switching to A*-style heuristic guidance before the heuristic is trustworthy. An unreliable value estimate can actively bias exploration away from the true optimum, which is worse than no guidance at all in some regimes, since blind BFS or DFS at least eventually covers the space, while a confidently wrong heuristic can systematically avoid it.
- Randomized variants (randomized DFS, epsilon-greedy frontier selection blending BFS and DFS) trade determinism for a middle ground: less worst-case memory than pure BFS, less worst-case commitment risk than pure DFS, at the cost of losing either strategy's clean guarantees (BFS's shallowest-first property, DFS's low memory bound) in the strict sense.
- Combining with intrinsic motivation (curiosity bonuses, count-based exploration bonuses that reward visiting novel states) is a complementary, not competing, technique: it changes WHICH states look attractive to explore, while the underlying BFS/DFS/heuristic choice still determines HOW the agent actually traverses toward whatever currently looks attractive.
Describe the adjacency list and adjacency matrix graph representations. For each, state the time and space complexity for common operations: iterate neighbors, check edge existence, add/remove an edge (for directed and undirected graphs). Given two example graphs (V=100000, E=200000) and (V=10000, E=80,000,000), recommend which representation you'd choose and why. Discuss tradeoffs for dynamic graphs and alternatives like CSR or edge-lists.
Sample Answer
Direct answer
An adjacency list stores, for each vertex, the list of its neighbors; it is compact for sparse graphs and is the default choice for most traversal algorithms. An adjacency matrix stores a V×V grid where entry (u,v) marks whether an edge exists; it gives constant-time edge lookups at the cost of O(V2) space regardless of how many edges actually exist. The right choice comes down to density: pick the list when edges are far fewer than V2 (the common case), pick the matrix when the graph is small and dense or when O(1) edge-existence checks dominate the workload.
Structured elaboration
Operation costs (V = number of vertices, E = number of edges, deg(u) = out-degree of u):
| Operation | Adjacency list | Adjacency matrix |
|---|---|---|
| Iterate neighbors of u | O(deg(u)) | O(V) (scan the row even for absent edges) |
| Check edge (u,v) exists | O(deg(u)) with a plain array; O(1) expected if each vertex's neighbors are stored in a hash set | O(1) |
| Add edge (u,v) | O(1) amortized (append) | O(1) |
| Remove edge (u,v) | O(deg(u)) to find and remove from an array; O(1) expected with a hash set | O(1) |
Directed vs undirected. For a directed graph, add/remove touch one entry. For an undirected graph, both representations must update the entry in both directions, (u,v) and (v,u), so the constant factor doubles but the complexity class does not change.
Space. Adjacency list: O(V+E) for a directed graph, or O(V+2E) for undirected since each edge is stored once per endpoint (still O(V+E) asymptotically, since 2E=O(E)). Adjacency matrix: O(V2) always, independent of how many edges are actually present.
Worked example
Graph A: V = 100,000, E = 200,000.
Adjacency list needs roughly V+E=300,000 entries (directed) or 500,000 (undirected), a few megabytes either way. The matrix needs V2=1010 entries. Even at 1 bit per entry that is 1010/8≈1.25×109 bytes, about 1.16 GiB, and at 1 byte per entry it is about 9.3 GiB. Those numbers are not literally impossible to allocate on a large machine, but the graph's own density (at most E/[V(V−1)]≈2.0×10−5, about 0.002%, if directed) means over 99.99% of the matrix's cells would encode "no edge." Adjacency list wins: same information in roughly 30,000x less space, with no capability lost for this workload.
Graph B: V = 10,000, E = 80,000,000. Before recommending anything, check whether this edge count is even achievable. The maximum number of edges in a simple undirected graph on 10,000 nodes is V(V−1)/2=49,995,000, which is less than the stated 80,000,000. So this graph can only be realized as directed (max V(V−1)=99,990,000, and 80,000,000 is about 80% of that, a genuinely dense digraph) or as a multigraph with parallel edges. Treating it as directed: adjacency matrix needs V2=108 entries, 100 MB at 1 byte per entry or 12.5 MB at 1 bit per entry. Adjacency list needs O(V+E)≈80,010,000 entries; even at a compact 4 bytes per neighbor id that is roughly 320 MB, several times larger than the byte-per-entry matrix. With the graph 80% full, most rows are nearly complete anyway, so the matrix's O(V) neighbor scan is not wasteful in practice. Recommendation: adjacency matrix for Graph B, adjacency list for Graph A.
Role-flavored variants of the same reasoning: a social-network adjacency graph (most users have a small, bounded number of connections relative to the total user count) is sparse like Graph A and belongs in an adjacency list, typically backed by hash sets so mutual-friend checks are O(1). A backend service's topology graph (which services call which) is usually small enough in vertex count that either representation fits in memory, but teams default to adjacency lists because service graphs are edited far more often than they are queried for raw connectivity. A machine learning engineer's graph choice usually tracks the same density argument: a sparse knowledge graph or citation graph behaves like Graph A, while a dense similarity graph or attention-weight graph over a small batch can behave like Graph B.
Trade-offs and pitfalls
- Dynamic graphs. Adjacency lists (especially backed by hash sets) handle frequent insert/delete well. Matrices give O(1) point updates but are expensive to grow, resizing V means reallocating an entire O(V2) structure.
- Compressed sparse row (CSR). Stores the graph as two flat arrays: an offsets array of size V+1 and a flattened neighbor array of size E. Same O(V+E) space as a list but contiguous memory, which gives far better cache locality when iterating neighbors repeatedly (as BFS/DFS/Dijkstra do). The cost is mutation: inserting one edge into a CSR structure generally requires rebuilding the offsets array, so CSR fits static or mostly-read graphs, not graphs under constant edit.
- Edge list. Stores raw (u,v[,w]) tuples, O(E) space, minimal overhead. Good for streaming ingestion and for algorithms that consume edges directly in some order (Kruskal's minimum spanning tree sorts the edge list by weight). Bad for neighbor iteration or existence checks unless you build an index on top.
- Common mistake: assuming a plain adjacency list gives O(1) edge-existence checks. A bare list of neighbors gives O(deg(u)); you only get O(1) by paying for a hash set per vertex, which costs more memory and constant-factor overhead than a plain dynamic array.
- Common mistake: picking a representation from a size label ("small graph" or "big graph") instead of computing the actual density. Graph B above looks intimidating at 80 million edges, but relative to its 10,000 nodes it is a dense graph that a matrix handles comfortably; a habit of always reaching for adjacency lists would have picked the wrong tool here.
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.
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.