Skip to content

Topological Sort — Course Schedule II ​

↗ LeetCode: Course Schedule II · Medium · pattern chapter →

Asked atMetaAmazonGoogleMicrosoftAppleBloomberg

Given numCourses and prerequisites[i] = [a, b] meaning "to take a you must first take b", return an ordering, or [] if impossible (cycle).

Example 1 — n=2, [[1,0]] → [0,1]Example 2 — n=4, [[1,0],[2,0],[3,1],[3,2]] → [0,1,2,3] or [0,2,1,3]Example 3 — n=2, [[1,0],[0,1]] → [] (cycle)

Constraints — 1 ≤ n ≤ 2000; 0 ≤ #prereqs ≤ n·(n−1)/2. Brute repeatedly scans for zero-indegree nodes: O(V·(V+E)) = 2000·(2000+5000) = 1.4·10⁷ ops. Kahn's queue-based BFS is O(V+E) = 7·10³ ops with built-in cycle detection.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Brute force (try every permutation) ​

Intuition. Enumerate every permutation; return the first that respects all prerequisites.

Complexity — Time O(n!) — impossible past n≈10.


Approach 2 — DFS with color marking (post-order) ​

Insight from brute. A course can be placed after all its prerequisites; DFS in post-order emits nodes in reverse topological order.

Use 3 colors: WHITE = unvisited, GRAY = on the current path (cycle detection), BLACK = finished.

Trap. If DFS revisits a GRAY node → cycle → return [].

java
int[] findOrderDFS(int n, int[][] prereqs) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] p : prereqs) adj.get(p[1]).add(p[0]);
    int[] color = new int[n];
    LinkedList<Integer> post = new LinkedList<>();
    for (int i = 0; i < n; i++) if (color[i] == 0 && !dfs(i, adj, color, post)) return new int[0];
    int[] out = new int[n];
    int k = 0;
    for (int x : post) out[k++] = x;
    return out;
}
boolean dfs(int u, List<List<Integer>> adj, int[] color, LinkedList<Integer> post) {
    color[u] = 1;                                       // gray
    for (int v : adj.get(u)) {
        if (color[v] == 1) return false;                // back-edge → cycle
        if (color[v] == 0 && !dfs(v, adj, color, post)) return false;
    }
    color[u] = 2;                                       // black
    post.addFirst(u);                                    // prepend for reverse post-order
    return true;
}

Complexity — Time O(V + E); Space O(V + E). Optimal.


Approach 3 — Kahn's algorithm (BFS on in-degrees) ​

Insight from DFS. Iteratively remove nodes whose in-degree is 0 — they are "always safe next." Repeat until empty (or cycle).

Bonus. Kahn's naturally returns the topological order forward-emitting (no reverse); easier for interviewers to trust.

java
int[] findOrder(int n, int[][] prereqs) {
    int[] indeg = new int[n];
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] p : prereqs) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
    Deque<Integer> q = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);
    int[] out = new int[n];
    int k = 0;
    while (!q.isEmpty()) {
        int u = q.poll();
        out[k++] = u;
        for (int v : adj.get(u)) if (--indeg[v] == 0) q.offer(v);
    }
    return k == n ? out : new int[0];                    // cycle → k < n
}
Execution Trace
Kahn — n=4, edges 0→1, 0→2, 1→3, 2→3
emitted00112233indeg = [0,1,1,2]queue = [0]
Step 1 / 5seed with in-degree 0

Complexity — Time O(V + E); Space O(V + E).


Try it yourself ​

Complexity summary ​

ApproachTimeSpace
PermutationsO(n!)O(n)
DFS post-orderO(V + E)O(V + E)
Kahn BFSO(V + E)O(V + E)

When to use which ​

  • Cold interview → Kahn is easier to explain and debug live.
  • DFS variant → useful when you also need SCC or bridges.
  • Cycle detection is the primary need → either works; DFS with color is cleaner.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help