Course Schedule II

Medium Graphs Topological Sort Original on LeetCode

Course Schedule II is a medium graphs problem solved with the topological sort pattern. The best approach, kahn's algorithm, runs in O(V + E) time and O(V + E) space. Below are 2 approaches in Java, from dfs postorder up.

Problem

Same setup as Course Schedule, but return an order in which you can take all courses. If it is impossible, return an empty array.

Examples

Example 1

Input
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output
[0, 1, 2, 3] or [0, 2, 1, 3]

Example 2

Input
numCourses = 2, prerequisites = [[0,1],[1,0]]
Output
[]

Constraints

  • 1 <= numCourses <= 2000.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
DFS postorderO(V + E)O(V + E)
Kahn's algorithmO(V + E)O(V + E)

1DFS postorder

TimeO(V + E)
SpaceO(V + E)

DFS with three states. Append each course after all courses that depend on it are finished, then reverse. A back edge means no order exists.

  1. Edges b → a. On finish, add u to the list.
  2. Reverse; return empty on a cycle.
Java
class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
        for (int[] p : prerequisites) adj.get(p[1]).add(p[0]);
        int[] state = new int[numCourses];
        List<Integer> post = new ArrayList<>();
        for (int i = 0; i < numCourses; i++)
            if (state[i] == 0 && !dfs(i, adj, state, post)) return new int[0];
        int[] out = new int[numCourses];
        for (int i = 0; i < numCourses; i++) out[i] = post.get(numCourses - 1 - i);
        return out;
    }

    private boolean dfs(int u, List<List<Integer>> adj, int[] state, List<Integer> post) {
        state[u] = 1;
        for (int v : adj.get(u)) {
            if (state[v] == 1) return false;
            if (state[v] == 0 && !dfs(v, adj, state, post)) return false;
        }
        state[u] = 2;
        post.add(u);
        return true;
    }
}

2Kahn's algorithm

TimeO(V + E)
SpaceO(V + E)

Output courses in the order they reach in-degree 0. If fewer than numCourses are output, a cycle blocked the rest.

  1. Queue zeros; pop into the order; decrement neighbours.
  2. Return the order if its size is numCourses, else an empty array.
Java
class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
        int[] indeg = new int[numCourses];
        for (int[] p : prerequisites) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
        Queue<Integer> q = new ArrayDeque<>();
        for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.add(i);
        int[] order = new int[numCourses];
        int k = 0;
        while (!q.isEmpty()) {
            int u = q.poll();
            order[k++] = u;
            for (int v : adj.get(u)) if (--indeg[v] == 0) q.add(v);
        }
        return k == numCourses ? order : new int[0];
    }
}

Edge cases to test

  • A cycle (return an empty array)
  • No prerequisites (any order)

Hints

Hint 1

It is Course Schedule, but you return the order Kahn's algorithm produces.

FAQ

What is the best time complexity for Course Schedule II?

Kahn's algorithm runs in O(V + E) time and O(V + E) extra space.

Which pattern does Course Schedule II use?

It is a graphs problem that uses the topological sort pattern. Other problems with the same pattern: Topological sort using BFS, Course Schedule, Alien Dictionary.

Is there a brute force solution for Course Schedule II?

Yes. DFS postorder takes O(V + E) time and O(V + E) space. DFS with three states.

Which edge cases should I test for Course Schedule II?

A cycle (return an empty array); No prerequisites (any order).