ExamAdda Logo

Course Schedule II

Easy

There are numCourses courses numbered from:

0 to numCourses - 1

 

You are given prerequisite pairs:

[a, b]

 

which means:

You must complete course b before taking course a.

 

Return an ordering of courses that allows you to finish all courses.

If it is impossible because of a cycle, return an empty array.

Example

numCourses = 4

prerequisites:

[1,0]

[2,0]

[3,1]

[3,2]

 

The dependencies are:

0 → 1

0 → 2

1 → 3

2 → 3

 

One valid order is:

0 1 2 3

 

Another valid order is:

0 2 1 3

 

Both are correct.

Main Idea

This is a Topological Sort problem.

We can use Kahn's Algorithm (BFS):

  1. Build the directed graph.
  2. Calculate the indegree of every course.
  3. Add all courses with indegree 0 to a queue.
  4. Remove courses one by one.
  5. Reduce the indegree of their neighboring courses.
  6. Whenever a course becomes 0, add it to the queue.
  7. If all courses are processed, return the ordering.
  8. Otherwise, a cycle exists → return empty array.

Example 1

Input

4 4
1 0
2 0
3 1
3 2

Output

0 1 2 3

Explanation

The prerequisites create:

0 → 1

0 → 2

1 → 3

2 → 3

 

Initially, only course 0 has no prerequisites.

So:

Queue:

0

 

Process 0:

1 and 2 become available

 

One possible processing order is:

0 → 1 → 2 → 3

 

Therefore:

[0,1,2,3]

 

is a valid answer.

Note: [0,2,1,3] is also valid.

Example 2

Input

2 2
1 0
0 1

Output

[]

Explanation

The dependencies are:

0 → 1

↑   ↓

└───┘

 

There is a cycle.

Course 0 requires 1, while course 1 requires 0.

Therefore, it is impossible to finish all courses.

Return:

[]

Constraints

1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai
bi < numCourses
All prerequisite pairs are unique.

Hints:

Hint 1

This is the same cycle-detection idea as Course Schedule, but now you must actually produce the course order.

Hint 2

Use indegree.

indegree[i] = number of prerequisites required before course i

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 16, 2026

Last updated

Aug 16, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output