Lesson 21 of 27Decode by category
Decoding Trees and Graphs
Decide between DFS, BFS, topological sort, union-find, and Dijkstra from words like shortest, levels, and dependencies.
Tree and graph questions rarely say "use BFS". They say "minimum number of minutes", "in what order can you take the courses", or "how many groups of friends". Each phrase maps to one algorithm almost every time, and recognising that mapping in the first minute is what lets you spend the rest of the interview on the details.
This lesson builds that map: first what kind of structure you have, then which traversal or algorithm the wording asks for. The algorithms themselves are taught in the Algorithms & Patterns course: Trees; Graphs; Union-Find in Depth; Shortest Paths: BFS, 0-1 BFS, Dijkstra, Bellman-Ford; and Cycles, Ordering and Bipartite Graphs.
Step one: tree, graph, or grid?
| You see | Structure | What it changes |
|---|---|---|
"root", "binary tree", TreeNode, "left and right child" | Tree | No cycles, one path between nodes. No visited set needed. |
| "edges", "connections", "prerequisites", "flights", "friends" | Graph | Cycles are possible. You must track visited nodes. |
| A 2D array of cells, moves "up, down, left, right" | Grid (an implicit graph) | Each cell is a node, neighbours are the 4 (or 8) adjacent cells. |
| A list of words where each step changes one letter | Implicit graph | You build the edges yourself, often on the fly. |
The grid case catches people out. Number of Islands never mentions graphs, but each land cell is a node and each pair of touching land cells is an edge. Once you see that, it is plain connected components.
A note on directed versus undirected: "a depends on b", "a must come before b", "a flight from x to y" are one-way edges. "a and b are friends" or "roads connect" are two-way. Get this right before you build the adjacency list.
Step two: which algorithm?
| Wording | Algorithm | Why |
|---|---|---|
| "shortest path", "minimum steps", "fewest moves" (no weights) | BFS | BFS visits nodes in order of distance, so the first time you reach the target is the shortest. |
| "level by level", "each depth", "right side view" | BFS | A queue processes one level fully before the next. |
| "nearest" from several sources at once, "minutes until all" | Multi-source BFS | Put every source in the queue at time 0. |
| "count the islands / groups", "can you reach", "explore all" | DFS (or BFS) | Any full traversal works; DFS is the shortest to write. |
| A value computed from children: height, diameter, balanced | DFS, post-order | You need the children's answers before the parent's. |
| "prerequisites", "order of tasks", "dependencies", "is it possible to finish" | Topological sort | A valid order exists exactly when the directed graph has no cycle. |
| "are these connected", "redundant edge", "merge accounts", edges arrive over time | Union-find | Near O(1) merge and same-group checks. |
| "cheapest", "minimum time" with weights on edges | Dijkstra | BFS is wrong when edges have different costs. Non-negative weights only. |
Levels mean BFS
Here is level-order traversal on a small tree. The queue holds exactly one level at a time, which is why "levels" is a BFS word.
The queue starts with the root. Level 0 is [3].
What does this print?
from collections import deque
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": []}
dist = {"A": 0}
queue = deque(["A"])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist:
dist[nxt] = dist[node] + 1
queue.append(nxt)
print(dist["E"])Weights mean Dijkstra
The moment edges carry different costs, "fewest edges" and "cheapest" stop being the same thing. Look at this graph.
We want the cheapest route from A to D.
The deciding clue is whether the prompt gives a number per edge: travel times, prices, effort. If every edge costs the same (or the prompt only counts steps), BFS is correct and simpler. If weights are only 0 or 1, a deque-based BFS works too, which is a nice thing to mention.
Dependencies mean topological sort
"Course B requires course A" is a directed edge A → B. "Can you finish all courses?" is "does this graph have a cycle?". "In what order?" is a topological order. Kahn's algorithm takes every node with no remaining prerequisites, removes it, and repeats.
Count incoming edges. Only Intro has zero, so it goes in the queue.
Connected means DFS or union-find
"How many groups?" on a fixed graph is a traversal: start DFS from each unvisited node and count how many times you start. Union-find shines when edges arrive one at a time and you must answer "are these connected yet?" after each, or when you need the first edge that creates a cycle (Redundant Connection).
Match the wording to the algorithm it points to.
The decision routine
Put these decode questions in the order you should ask them.
- Tap the steps below in the right order.
State complexity in terms of the graph: "O(V + E) for BFS or DFS, where V is the number of nodes and E the number of edges. On an n by m grid that is O(n · m)." Dijkstra with a binary heap is O(E log V). Union-find with path compression and union by rank is close to O(1) per operation.
Use the Decoder on graph problems and pay attention to the clue stage: most graph prompts hide the structure in story words like "rooms", "cities", or "accounts".
Rotting Oranges
A crate is a grid where 0 is an empty slot, 1 is a fresh orange and 2 is a rotten one. Every minute, each rotten orange rots the fresh oranges directly above, below, left and right of it. Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never be reached.
[[2, 1, 1],
[1, 1, 0],
[0, 1, 1]] → 4
[[2, 1, 1],
[0, 1, 1],
[1, 0, 1]] → -1 (bottom-left orange is cut off)
[[0, 2]] → 0 (nothing fresh to begin with)Constraints
1 <= grid.length, grid[i].length <= 10grid[i][j]is0,1or2
Course Schedule
There are num_courses courses labelled 0 to num_courses - 1. Each pair [a, b] in prerequisites means you must finish course b before course a. Return true if you can finish every course, and false if the requirements make that impossible.
num_courses = 2, prerequisites = [[1, 0]] → true
num_courses = 2, prerequisites = [[1, 0], [0, 1]] → false (each needs the other)
num_courses = 3, prerequisites = [] → trueConstraints
1 <= num_courses <= 20000 <= prerequisites.length <= 50000 <= a, b < num_courses
- implicit graph
- A graph you never get as edges, such as a grid of cells or words one letter apart.
- multi-source BFS
- BFS that starts with several nodes in the queue at distance 0, for simultaneous spreading.
- topological sort
- An order of a directed graph's nodes where every edge points forward. Exists only if there is no cycle.
- union-find
- A structure that merges groups and answers 'same group?' in near constant time.
- Dijkstra
- Shortest paths with non-negative weights, always expanding the cheapest known node using a min-heap.
- O(V + E)
- The cost of a full BFS or DFS: every node and every edge is handled once.