This practice workspace is built for desktop. Open it on a larger screen to start solving.
Course Schedule II
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [a, b] indicates that you must take course b first if you want to take course a.
Return any valid order in which you can take all courses. If it is impossible to finish all courses (i.e. the prerequisite graph has a cycle), return an empty array [].
Determinism. When multiple valid orderings exist, return the one produced by Kahn's algorithm with ties broken by ascending course number — i.e. at every step, among the indegree-zero nodes, take the smallest-numbered course first. The reference solution implements this with a min-heap (Python: heapq; JavaScript: a small inline MinHeap).
Self-loops are cycles, so [[0, 0]] returns [].
Examples
Constraints
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= numCourses * (numCourses - 1)
- prerequisites[i].length == 2
- 0 <= a, b < numCourses
Preview Mode
This is a read-only preview of DSAMind's AI coaching. Sign up to get custom feedback on your own solution.
Your approach
- Pattern:Graphs
- Time:O(N)
- Space:O(1)
Complete approach — pattern and complexity both named.
Coach
What you got right
You correctly matched the sorted input requirement and implemented a linear-time scan using two pointers.
Where it diverged
No divergence detected. The code correctly aligns with the stated approach.
Next attempt: focus on
Try solving related sliding window problems to build familiarity with two-pointer variants.
Signals
No signals fired — clean run, you stayed in flow.