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.
Explain the formal differences between a tree and a general graph. Describe properties that define a tree (connected, acyclic, exactly n-1 edges for n nodes), implications such as unique simple path between nodes, and how those properties simplify algorithms (e.g., no need for visited set in some traversals). Give concrete examples of when you'd model a problem as a tree versus as a general graph.
Sample Answer
Direct answer
A tree is a special case of a graph: connected, acyclic, and with exactly n−1 edges for n nodes. Those three properties are not independent facts to memorize separately, any two of them imply the third for a graph on n nodes (connected and acyclic implies exactly n−1 edges; connected with n−1 edges implies acyclic; acyclic with n−1 edges implies connected). The single most useful consequence is that a tree has EXACTLY ONE simple path between any two nodes, which is what lets several algorithms drop bookkeeping that a general graph requires.
Structured elaboration
The defining properties.
- Connected: every node is reachable from every other node.
- Acyclic: no sequence of edges returns to a starting node without repeating an edge.
- Exactly n−1 edges: the minimum number of edges that can connect n nodes (fewer would leave the graph disconnected), and simultaneously the maximum a connected graph can have before a cycle becomes unavoidable.
Why unique simple paths follow. If two different simple paths existed between the same pair of nodes u and v, combining them (going from u to v along one path and back along the other) would trace out a cycle, since the two paths, taken together, revisit u without repeating any single edge twice. This contradicts acyclicity, so at most one simple path can exist; connectivity guarantees at least one exists; together, exactly one.
How this simplifies algorithms. A general graph traversal (breadth-first search (BFS) or depth-first search (DFS)) needs a visited set specifically to avoid two things a tree traversal never has to worry about: re-processing a node reached by more than one route (impossible in a tree, since only one route exists), and looping forever around a cycle (impossible, since there are none). A tree traversal from a chosen root still benefits from tracking "the parent I came from" to avoid immediately walking back the edge just traversed, but that is a much lighter requirement than a full visited set, since it only needs to exclude one specific neighbor (the parent), not remember an arbitrarily large set of everywhere already visited. This is also why tree algorithms can often be written as a clean recursive function of "process this node, then recurse into every neighbor except the parent," with no separate visited-tracking data structure at all.
Worked example
Model as a tree: an organizational reporting hierarchy (each employee has exactly one manager, forming a rooted tree), a filesystem directory structure (each file or folder has exactly one parent directory, ignoring symbolic links), or a binary decision tree used for classification (each internal node has exactly one path down from the root). In each case, "does A report (transitively) to B" or "what is the path from the root to this file" has exactly one answer, and that answer can be found by walking up parent pointers without ever needing to consider an alternative route.
Model as a general graph: a social network (a person can be connected to many others through multiple independent paths, and cycles like mutual-friend triangles are common and meaningful), a service-dependency graph (multiple services may all depend on a shared cache, creating multiple paths between two other services through it), or a road network (there are almost always multiple ways to get from one intersection to another). Forcing any of these into a tree structure would either lose real information (dropping legitimate alternate paths) or require artificially picking one "true" parent per node, discarding the graph's actual shape.
A concrete boundary case worth naming: a graph can look tree-like in casual description ("each task depends on its predecessor") while actually being a directed acyclic graph (DAG), not a tree, the moment a task has more than one direct dependency (two edges pointing INTO the same node). A DAG is still acyclic, but multiple parents mean it is not a tree, and it does not get the "exactly one path between any two nodes" guarantee, a build system's dependency graph is the standard example: a shared library can be a prerequisite for many independent components at once, giving that library multiple incoming edges from unrelated parts of the graph.
Trade-offs and pitfalls
- Common mistake: treating "acyclic" and "tree" as synonyms. A DAG is acyclic but can have nodes with multiple parents (multiple incoming edges), which breaks the unique-simple-path property that trees rely on; algorithms that assume tree structure (a plain parent-pointer walk with no visited set) will double-count or infinite-loop-free-but-redundantly-revisit shared nodes in a DAG, even though the DAG has no cycle to get stuck in.
- Common mistake: assuming "connected with no cycles found so far" is the same as "is a tree," without separately checking the edge count. A connected graph with n nodes and MORE than n−1 edges necessarily contains a cycle (by the same counting argument that shows n−1 is the connectivity-preserving maximum), so if a traversal reports "no cycle found" on a graph that was never checked for edge count, that traversal may simply not have reached the cycle-forming edge yet, especially in a partial or early-terminated search.
- Real systems often START as trees and DRIFT into general graphs as requirements grow: an initial single-parent category hierarchy in a product catalog is a tree, but the moment a product needs to belong to two categories at once (multiple parents), the structure is a DAG, and any code written assuming a tree (recursive descent with no cycle guard, path-uniqueness assumptions in a breadcrumb trail) needs to be revisited, not just extended.
- When in doubt about which structure a system actually has, the edge-count check is cheap and decisive: count edges, count nodes, and confirm ∣E∣=∣V∣−1 AND connectivity before relying on any tree-only simplification; skipping this and assuming "it's basically a tree" is a common source of subtle graph-traversal bugs once the data eventually violates the assumption.
Explain cycle detection techniques for directed graphs, including DFS coloring (white/gray/black) and recursion-stack detection. Provide a concise Python pseudocode sketch for DFS coloring, discuss self-loops and parallel edges, and explain why union-find alone is insufficient for directed cycle detection.
Sample Answer
Direct answer
DFS coloring (white/gray/black) and recursion-stack detection are the same technique described two different ways: both mark a node as "currently on the active exploration path" the moment depth-first search (DFS) enters it, and unmark it the moment DFS finishes with it, so that an edge into a still-marked node is recognized as a back edge, a genuine cycle. Union-find (disjoint-set), by contrast, is fundamentally an UNDIRECTED-connectivity structure: it can only tell you "these two nodes are in the same component," never "is there a directed path from one back to the other," which is exactly what directed cycle detection actually requires, and applying it naively to a directed graph produces false positives on ordinary, acyclic shared-descendant structures.
Structured elaboration
DFS coloring, precisely. White means undiscovered. Gray means discovered and still being explored, equivalently, "on the current recursion stack." Black means fully finished, every node reachable from it has already been explored. When DFS at node u examines an edge to neighbor v: white means recurse into v; gray means v is an ancestor of u on the current path, a back edge, a cycle; black means v was already fully explored via some unrelated path, not a cycle.
Recursion-stack detection is the identical idea under a different name. Instead of three colors, maintain a boolean array inStack, set true when DFS enters a node and reset to false when DFS finishes with it (backtracks past it). "Gray" and "on the recursion stack" are the exact same set of nodes at every point in the traversal; the two formulations differ only in bookkeeping style (an enum-like color per node, versus a separate boolean array), not in what they detect or how.
Why union-find alone is insufficient for directed graphs. Union-find answers "are u and v already connected by SOME path, in either direction?" It has no notion of edge direction at all: union(u, v) merges two components regardless of which way the edge points. Consider the DIAMOND shape 0→1, 1→3, 0→2, 2→3: this is a perfectly acyclic DAG (directed acyclic graph), node 3 is simply a shared descendant of both 1 and 2. But processing these edges through undirected union-find: union(0,1), union(1,3), union(0,2) all succeed (new components merging), then union(2,3) finds find(2) and find(3) ALREADY in the same component (both merged in via 0-1-3 and 0-2 respectively) and reports a "cycle" that does not actually exist in the directed graph. Union-find cannot distinguish "these nodes are connected because of a legitimate shared ancestor/descendant" from "these nodes are connected because of an actual directed loop," because it discards direction entirely the moment an edge is unioned.
Worked example
Concise Python pseudocode sketch, DFS coloring:
def has_cycle(graph):
color = {v: "white" for v in graph}
def dfs(u):
color[u] = "gray"
for v in graph[u]:
if color[v] == "white":
if dfs(v):
return True
elif color[v] == "gray":
return True # back edge -> cycle
color[u] = "black"
return False
for node in graph:
if color[node] == "white" and dfs(node):
return True
return False
if __name__ == "__main__":
dag = {0: [1, 2], 1: [3], 2: [3], 3: []}
print("DAG (no cycle):", has_cycle(dag))
cyclic = {0: [1], 1: [2], 2: [0]}
print("cyclic:", has_cycle(cyclic))
self_loop = {0: [0]}
print("self-loop:", has_cycle(self_loop))
parallel_edges = {0: [1, 1], 1: []}
print("parallel edges, no cycle:", has_cycle(parallel_edges))
diamond_no_cycle = {0: [1, 2], 1: [3], 2: [3], 3: []}
print("diamond shared descendant, no cycle:", has_cycle(diamond_no_cycle))
Output (actually executed with python3):
DAG (no cycle): False
cyclic: True
self-loop: True
parallel edges, no cycle: False
diamond shared descendant, no cycle: False
And, isolating the union-find false-positive claim specifically, running the diamond's edges through a plain, undirected union-find:
class UF:
def __init__(self, n):
self.p = list(range(n))
def find(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]
x = self.p[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
self.p[ra] = rb
return True
edges = [(0, 1), (1, 3), (0, 2), (2, 3)] # the same acyclic diamond DAG
uf = UF(4)
false_positive = any(not uf.union(u, v) for u, v in edges)
print("Union-find (undirected) falsely flags this acyclic diamond DAG as cyclic:", false_positive)
Output (actually executed with python3):
Union-find (undirected) falsely flags this acyclic diamond DAG as cyclic: True
This is a direct, executed confirmation of the claim: the exact same diamond shape that DFS coloring correctly reports as acyclic (False above) is INCORRECTLY reported as cyclic by naive undirected union-find, which is precisely why union-find alone cannot be used for directed cycle detection.
Edge cases
- Self-loops: an edge u→u is caught immediately, since u is still gray (it just entered) when its own edge is examined; no special-casing is needed, though a caller who wants to deliberately IGNORE self-loops (treat them as valid, common in some dependency-graph conventions) needs to explicitly skip
v == ubefore the color check. - Parallel edges (multiple edges between the same ordered pair): correctness is unaffected, since a repeated edge to an already-black or already-white neighbor is evaluated the same way each time; the only cost is wasted iteration if the neighbor list contains true duplicates, worth de-duplicating at ingestion if the graph is expected to have many.
Trade-offs and pitfalls
- Common mistake: reaching for union-find on a directed cycle-detection task because it "worked for undirected cycle detection," without checking whether direction actually matters for the graph at hand; the diamond example above is exactly the shape that exposes this mistake in the smallest possible test case, and is worth keeping as a permanent regression test for any codebase where this confusion has happened once.
- Common mistake: implementing recursion-stack detection with a SHARED
inStackarray across multiple independent DFS calls (from different starting nodes in the same traversal) but forgetting to reset it correctly on backtrack, which can cause a node correctly finished and popped off one branch's stack to be mistaken for still being on-path when a completely different branch later reaches it. - When union-find IS the right tool. For UNDIRECTED cycle detection specifically (does an undirected graph, as opposed to a directed one, contain a cycle), union-find is both correct and often simpler than DFS with parent-tracking, since undirected connectivity is exactly what it was built to answer; the insufficiency here is specific to the directed case, not a general weakness of the data structure.
- Performance. Both DFS-based techniques are O(V+E); union-find with path compression and union by rank is O(Eα(V)) for the undirected case it is actually suited to, effectively linear, so there is no performance argument for reaching past DFS coloring toward union-find on a directed graph, only a correctness argument against doing so.
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.
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.
Solve the maximum weight independent set on a tree: given a tree where each node has a non-negative weight, select a set of nodes with no adjacent nodes maximizing total weight. Implement in Python with O(N) time using tree DP. Provide signature: def max_independent_set(adj: Dict[int, List[int]], weights: Dict[int,int]) -> int and explain your DP states.
Sample Answer
Direct answer
This is tree DP: root the tree at any node, and for each node compute two values, the best achievable weight of an independent set in that node's subtree WHEN the node itself is included, and the best when it is EXCLUDED. If a node is included, none of its direct children may be included (so each child contributes its own "excluded" value), and if a node is excluded, each child is free to contribute whichever of its own two values is larger. The answer is the max of the root's two values, computed bottom-up in a single post-order depth-first search (DFS), giving O(N) time since each node is visited once and does O(1) work beyond its recursive calls.
Structured elaboration
Why "included" and "excluded" as the two DP states. An independent set on a tree forbids any two ADJACENT nodes both being chosen. On a tree, adjacency is exactly the parent-child relationship, so the only constraint that ever needs enforcing at any node is between that node and its direct children, not any deeper relationship (a node and its grandchild are never adjacent, so no constraint links them directly; the constraint propagates only through the recursive excluded values, correctly capturing that a grandchild's INCLUSION is not blocked by the root's inclusion, only a direct child's is).
Recurrence. For node u with children c_1, ..., c_k:
incl(u)=w(u)+∑iexcl(ci)
excl(u)=∑imax(incl(ci),excl(ci))
The base case (a leaf with no children) is incl(leaf) = w(leaf), excl(leaf) = 0 (both sums over an empty child list are 0, so the general recurrence already handles leaves correctly without a separate base case).
Why a single post-order pass suffices, no memoization table needed beyond the two per-node values. Each node's incl/excl values depend only on its CHILDREN's incl/excl values, never on anything computed later in a different subtree, so a straightforward post-order DFS (compute all children first, then the current node) naturally produces every value exactly once, in the right dependency order, with no need for a separate memo dictionary keyed by subproblem, unlike DP on a general DAG where multiple paths to the same subproblem can require explicit memoization to avoid recomputation.
Worked example
import sys
from typing import Dict, List
def max_independent_set(adj: Dict[int, List[int]], weights: Dict[int, int]) -> int:
sys.setrecursionlimit(10000)
root = next(iter(adj))
visited = {root}
def dfs(u):
incl = weights[u]
excl = 0
for v in adj.get(u, []):
if v in visited:
continue
visited.add(v)
child_incl, child_excl = dfs(v)
incl += child_excl
excl += max(child_incl, child_excl)
return incl, excl
incl_root, excl_root = dfs(root)
return max(incl_root, excl_root)
if __name__ == "__main__":
# 0(w=6)
# / \
# 1(w=8) 2(w=5)
# | \
# 3(w=3) 4(w=9)
adj = {0: [1, 2], 1: [0, 3], 2: [0, 4], 3: [1], 4: [2]}
weights = {0: 6, 1: 8, 2: 5, 3: 3, 4: 9}
result = max_independent_set(adj, weights)
print("weights:", weights)
print("max independent set weight:", result)
Output:
weights: {0: 6, 1: 8, 2: 5, 3: 3, 4: 9}
max independent set weight: 18
Trace: leaves 3 and 4 have incl=3, excl=0 and incl=9, excl=0 respectively. Node 1: incl = 8 + excl(3) = 8 + 0 = 8, excl = max(incl(3), excl(3)) = max(3, 0) = 3. Node 2: incl = 5 + excl(4) = 5 + 0 = 5, excl = max(incl(4), excl(4)) = max(9, 0) = 9. Root 0: incl = 6 + excl(1) + excl(2) = 6 + 3 + 9 = 18, excl = max(incl(1),excl(1)) + max(incl(2),excl(2)) = max(8,3) + max(5,9) = 8 + 9 = 17. Final answer max(18, 17) = 18, matching the printed output; the optimal set turns out to be {0, 3, 4} (root plus both "excluded child" leaves, weight 6+3+9=18), correctly skipping the higher-weight node 4's parent 2 in favor of taking node 4 itself rather than its parent.
Trade-offs and pitfalls
- Correctness cross-check performed against brute force: for this 5-node tree, every one of the 25=32 possible node subsets was enumerated, independence was checked against all 4 tree edges, and the maximum-weight valid subset was found by brute force to also be 18, confirming the DP's answer exactly matches exhaustive search on this instance.
- Common mistake: writing
excl(u) = max of all children's incl, or all children's excl(picking one branch for ALL children uniformly) instead of taking the max INDEPENDENTLY per child. Each child's contribution toexcl(u)should bemax(incl(c_i), excl(c_i))computed separately for each child, since different children can independently be in their own best state; forcing a single uniform choice across all children would understate the achievable weight whenever the best choice differs child to child. - Recursion depth is O(height), which is O(N) in the worst case (a tree that degenerates into a long chain); a production implementation accepting untrusted or adversarially shaped trees should convert this to an iterative post-order traversal with an explicit stack to avoid a
RecursionErroron a deep, path-like tree. - This recurrence is specific to TREES (a graph with no cycles and a single path between any two nodes). On a general graph, maximum weight independent set is NP-hard; the polynomial-time DP here relies entirely on the tree structure guaranteeing that removing the root splits the problem into completely independent subproblems (the children's subtrees), a decomposition that does not exist for a graph with cycles.
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.