Ctrl K

Course Enrollment Queue

Medium
An online school offers n courses numbered 0 to n - 1. A pair [a, b] in deps means course a can only be started once course b is finished. Students go through the courses using a single queue: - at the very start, every course with no requirements joins the queue, in ascending order of number; - courses are taken one at a time, always the one at the front of the queue; - when a course is finished, every course for which it was the last unfinished requirement joins the back of the queue; if there are several, they join in ascending order of number. Return the course numbers in the order they get finished. If it is impossible to finish all n courses this way, return an empty list.
Example 1
n=5, deps=[[3, 0], [1, 3], [4, 2], [1, 4]] → [0, 2, 3, 4, 1]

Courses with no requirements join the queue first: 0 and 2. Finishing 0 unlocks 3, finishing 2 unlocks 4. Course 1 needs both 3 and 4, so it joins last: 0, 2, 3, 4, 1.

Example 2
n=4, deps=[[2, 1], [1, 2], [3, 0]] → []

Courses 1 and 2 require each other, so not every course can be finished and the answer is empty.

Example 3
n=3, deps=[] → [0, 1, 2]
Constraints
  • 1 ≤ n ≤ 2000
  • 0 ≤ len(deps) ≤ 5000
  • deps[i] = [a, b], 0 ≤ a, b < n, a ≠ b
  • All pairs in deps are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsModule Build Order MediumBest Roots for a Tree MediumRoutes That Always End MediumLongest Hike Through the Woods MediumDoes This Step Come First Medium
loading Python…
Input
n=5, deps=[[3, 0], [1, 3], [4, 2], [1, 4]]
Expected
[0, 2, 3, 4, 1]

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.