Skip to content
Decoder

Course Schedule II

Medium

Problem

There are num_courses courses labelled 0 to num_courses - 1. Each pair [a, b] in prerequisites means course b must be taken before course a. Return an order in which you can take every course. If several orders work, any of them is accepted. If it is impossible, return an empty list.

Example 1

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

Example 2

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

Example 3

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

Constraints

  • 1 <= num_courses <= 2000
  • 0 <= prerequisites.length <= num_courses * (num_courses - 1)
  • 0 <= a, b < num_courses, and no pair appears twice

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.