Course Schedule II
Problem Statement
There are numCourses courses, labelled 0 to numCourses − 1. Each pair [a, b] in prerequisites means you must finish course b before you can take course a.
Return an order in which you can take all the courses. If several orders work, return any one of them. If no order works (the prerequisites form a loop), return an empty list.
numCourses, and prerequisites, a list of pairs [a, b].
A list with every course once, in an order that respects every pair. Or an empty list when no such order exists.
To take course 1 you must finish course 0 first, so 0 comes before 1.
Course 0 needs nothing. Courses 1 and 2 both need only 0. Course 3 needs both 1 and 2, so it comes last.
Course 0 needs 1 and course 1 needs 0. Neither can be taken first, so there is no valid order.
- • 1 ≤ numCourses ≤ 2000
- • 0 ≤ prerequisites.length ≤ numCourses · (numCourses − 1)
- • prerequisites[i].length == 2
- • 0 ≤ a, b < numCourses
- • a ≠ b
- • All the pairs [a, b] are distinct.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Each round, take the first course whose prerequisites are all taken; stop when none is free
Count prerequisites once; queue the courses with none left; return [] if not all were taken
Keep track of the taken courses. In each round, rebuild the list of blocked courses from all the pairs, take the first course that is not blocked, and repeat. If a round finds no free course while some are left, they wait on each other, so return an empty list.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.