Course Schedule

Medium

Question

You're given the total number of courses you need to take. You're also given a 2D list of the prerequisites for each course.

For example, [(4, 1), (2, 3)] means that you need to take course 4 BEFORE you can take course 1, and that you need to take course 2 BEFORE you can take course 3.

Return the ordered class schedule you can follow to finish all courses. If it's impossible to finish all courses, return an empty list.

Input: total = 2, prereqs = [(0, 1)]

Output: [0, 1]

You have to take course 0 before course 1. So you take course 0 first, then course 1.

Input: total = 2, prereqs = [(0, 1), (1, 0)]

Output: []

Here, the two courses are prerequisites of each other. That means there's no way to finish both.

Input: total = 5, prereqs = [(0, 2), (1, 2), (2, 4), (3, 4)]

Output: [0, 1, 3, 2, 4]

This order takes every course after its prerequisites.

Other orders would count as correct answers too:
  • [1, 0, 3, 2, 4]
  • [1, 3, 0, 2, 4]
  • [0, 3, 1, 2, 4]

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

What course schedule should the following input return? total = 3, prereqs = [(0, 1), (1, 2), (2, 0)]
[]
[0, 1, 2]
[2, 1, 0]
[2, 0, 1]

Remember to understand the problem and plan your approach before you start coding.