Pattern this teaches:Topological Sort
Course Schedule II
A medium Graph interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Graph
- Sheets
- 2
- Core for
- 12 roles
The problem
There are numCourses courses numbered 0 to numCourses - 1, and each prerequisite pair says one course must be finished before another. Return an order in which all courses can be taken. If the prerequisites form a cycle, no order exists; return an empty array.
Example 1
- Input
- numCourses = 3, prerequisites = [[1,0],[2,1]]
- Output
- [0,1,2]
- Why
- Each course unlocks the next: 0, then 1, then 2.
Example 2
- Input
- numCourses = 5, prerequisites = [[1,0],[2,1],[3,2],[4,3]]
- Output
- [0,1,2,3,4]
- Why
- A single chain of prerequisites leaves exactly one valid order.
Constraints
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= 5000
How to think about it
Updated 2026-09-29Topological sort linearizes dependencies: courses with no remaining requirements can be taken immediately. Recording each course as its prerequisites reach zero yields a valid progression, and if the resulting schedule falls short of numCourses, a deadlock prevented completion.
Approaches, worst first
DFS post-order with reverse output
time O(V + E) · space O(V + E)
Run cycle-detecting DFS across all nodes using visited status arrays. When all dependents of a course are resolved, push it to an ordering list and reverse the list at the end. Aborts with an empty array if any cycle is detected.
Kahn BFS peeling zero-indegreesWrite this one
time O(V + E) · space O(V + E)
Compute in-degrees for all vertices and push all nodes with in-degree 0 into a queue. Pop courses one by one directly into the output array, reducing in-degrees of neighbors. If the output array size matches numCourses return it, otherwise return empty.
Where people lose marks · 3
- Returning the partial array instead of an empty array `[]` when a cycle prevents all courses from being scheduled.
- Prerequisites array can be empty (length 0), where every course is independent and valid answers include any permutation such as `[0, 1, ..., numCourses - 1]`.
- Forgetting that multiple valid topological orderings exist; asserting equality against a single rigid test output instead of verifying prerequisite constraints breaks local tests.
The theory behind it
Graph — the ground this problem stands on. All Graph problems
What Graph is
A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.
When to reach for it
Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.
How the pattern works
First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.
More Graph problems
Target Roles
Core requirement for 12 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .