This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Phase 3: Search and graphs
Things with prerequisites: peel off whatever has nothing left blocking it.
Builds on Graph BFS & DFS.
The question to ask
Do the edges mean one thing must happen before another, and do I need an order or to detect a cycle?
When edges mean "must come before" (courses and prerequisites, build steps, recipes and ingredients), the question is either "give me a valid order" or "is there a cycle that makes any order impossible". Kahn's algorithm answers both: count each node's incoming edges, queue the ones with none, and every time you take a node, decrement its neighbours and queue any that hit zero. If you take fewer nodes than exist, there was a cycle.
Time O(V + E) · Space O(V + E)
Write it from memory first, in an editor or on paper, then check. Recalling it is what makes it stick; reading it again mostly doesn't.
The other classic: 0 is unvisited, 1 is on the current path, 2 is finished. Meeting a 1 again means a back edge, so a cycle. Reversed finish order is a topological order.
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
const next: number[][] = Array.from({ length: numCourses }, () => []);
for (const [course, before] of prerequisites) next[before].push(course);
const state = new Array<number>(numCourses).fill(0);
function hasCycle(node: number): boolean {
if (state[node] === 1) return true;
if (state[node] === 2) return false;
state[node] = 1;
for (const after of next[node]) if (hasCycle(after)) return true;
state[node] = 2;
return false;
}
for (let i = 0; i < numCourses; i++) if (hasCycle(i)) return false;
return true;
}Easy to hard. Read the prompt and name the signal before opening the tell. After each attempt, rate it: Again brings it back tomorrow, Hard holds the interval, Good and Easy push it further out.
In a town of n people, the judge trusts nobody and everybody else trusts the judge. Given who trusts whom, find the judge or return -1.
"Trusts" as directed edges: the judge has in-degree n - 1 and out-degree 0. In-degree counting is the first half of Kahn's.
Not attempted yet
There are numCourses courses and pairs of prerequisites. Can you finish all courses, or does a cycle of prerequisites make it impossible?
"Prerequisites" and "finish all": can a topological order exist, which is the same as no "cycle".
Not attempted yet
Return a valid ordering of courses that satisfies all prerequisites, or an empty array if impossible.
"Valid ordering" under "prerequisites": Kahn's algorithm, returning the order instead of a boolean.
Not attempted yet
A node is safe if every path from it leads to a terminal node. Return all safe nodes of the directed graph in sorted order.
"Safe" means it can't reach a cycle: reverse the edges and run Kahn's from the terminal nodes, or use three-colour DFS.
Not attempted yet
Given a tree of n nodes, return the roots that give the tree minimum height.
Peel leaves layer by layer, like Kahn's on an undirected tree; the last one or two nodes standing are the centres.
Not attempted yet
Given prerequisites, answer queries asking whether course u is a prerequisite, directly or indirectly, of course v.
Indirect "prerequisite" queries: process in topological order and pass each course's set of ancestors to its dependents.
Not attempted yet
Items belong to groups, and some items must come before others. Order items so each group is contiguous and all dependencies hold.
Two layers of "dependencies": topologically sort the groups, then the items inside each group.
Not attempted yet