Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

An order to take every course

Medium · Target 20 minutes · Graphs · Type asked atAmazonGoogleMeta

There are n courses numbered 0 to n − 1. Each pair [a, b] in prereqs means course b must be taken before course a. One course is taken at a time.

Return an order in which all n courses can be taken. Many orders may be valid: return the one that is smallest in dictionary order, that is, at every step take the smallest-numbered course whose prerequisites are all done. If no order exists, return an empty list.

Examples

InputOutputWhy
n = 4, prereqs = [[1,0],[2,0],[3,1],[3,2]][0, 1, 2, 3]0 first; then 1 and 2 are both available and 1 is smaller; 3 needs both.
n = 2, prereqs = [[1,0],[0,1]][]Each course needs the other.
n = 4, prereqs = [[0,1],[1,2],[2,3]][3, 2, 1, 0]A chain run backwards: 3 has no prerequisite.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ prereqs.length ≤ 5000
  • a ≠ b; no pair is repeated

Hints

Hint 1

Draw an edge b → a for each pair [a, b]. A course can be taken when its in-degree, counting only courses not yet taken, is zero.

Hint 2

Kahn's algorithm takes any course with in-degree zero. To get the smallest order, always take the smallest one: keep the available courses in a min-heap.

Hint 3

If the heap empties before every course is taken, the remaining courses are on or behind a cycle: return [].

Where people lose marks

  • Building the edge a → b instead of b → a, which produces a reversed order.
  • Using a plain queue and returning a valid but not the smallest order.
  • Returning the partial order when a cycle stops the algorithm, instead of an empty list.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.