Unlock Order: Build a Dependency-Respecting Study Plan
Trees & GraphsAuto-graded · 23 test casesLast updated
Produce a deterministic topological ordering of nodes from prerequisite pairs, or an empty list if a cycle makes it impossible. Tests graph modeling and Kahn's algorithm.
Unlock Order
A program has num_courses courses, numbered 0 to num_courses - 1. The requirements are given as a list of pairs. A pair [a, b] means course b must be completed before course a can be started.
Return a single list containing every course exactly once, in an order where each course appears after all of its prerequisites. If no such order exists because the requirements contain a cycle, return an empty list.
Required output order
Many valid orders can exist, but your function must return one specific order so that results can be checked exactly. Produce it with this procedure:
- For every course, count how many pairs name it as the first element (
a). This is the number of prerequisites it is still waiting on. - For every course
b, keep a list of the courses it unlocks. Build each list in the order the pairs appear inrequirements. - Create a first-in-first-out queue and add every course that has zero prerequisites, in increasing numeric order.
- While the queue is not empty:
- Remove the course at the front and append it to the result.
- Go through the courses it unlocks, in the stored order. Reduce each one's waiting count by 1. If the count reaches 0, add that course to the back of the queue.
- If the result contains all
num_coursescourses, return it. Otherwise return[]. Do not return a partial list.
A pair of the form [a, a] is a cycle, so the answer is [].
Constraints
1 <= num_courses <= 20000 <= len(requirements) <= num_courses * (num_courses - 1) / 2- Every pair in
requirementsis unique. - Every course number in a pair is in the range
0tonum_courses - 1.
Examples
Example 1
Input: plan_study_order(2, [[1, 0]])
Output: [0, 1]
Example 2
Input: plan_study_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 3
Input: plan_study_order(2, [[1, 0], [0, 1]])
Output: []
Hints
Hint 1
Treat each course as a node. A pair [a, b] is a directed edge from b to a, because completing b helps unlock a.
Hint 2
Track for each course how many prerequisites remain. Courses with none remaining can be taken immediately, so they go into the queue first.
Hint 3
After processing, compare the length of your result with the number of courses. If it is smaller, some courses were stuck behind a cycle, so return an empty list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a topological sort, and Kahn's algorithm fits it directly.
- Model each pair
[a, b]as an edgeb -> a. Store, for each course, the list of courses it unlocks. Also store how many prerequisites each course still waits on. - Put every course with zero waiting prerequisites into a FIFO queue, in increasing order.
- Repeatedly take the front course and append it to the result. For each course it unlocks, decrement the waiting count. When a count reaches zero, push that course onto the queue.
- If the result holds all courses, return it. Otherwise a cycle blocked some courses, so return
[].
The statement fixes the queue seeding order, the FIFO discipline and the order of the unlock lists, so the output is unique and matches exactly.
Why it is correct
- Valid order. A course enters the queue only when all of its prerequisites have already been appended, so every prerequisite precedes the courses that depend on it.
- Cycles are detected. Every course on a cycle has a prerequisite on that same cycle. Its waiting count can never reach zero before another cycle member is emitted, so none of them is ever emitted. The result is then shorter than
num_courses, and we return[]. Courses that depend on a cycle are blocked as well. - Acyclic input is fully processed. Any finite acyclic graph has at least one node with no incoming edges. Removing it leaves an acyclic graph, so by induction every course is emitted.
Complexity
With V = num_courses and E = len(requirements):
- Time:
O(V + E). Each course is queued once and each requirement is relaxed once. - Space:
O(V + E)for the unlock lists, the counts, the queue and the result.
Reference solution
from collections import deque
from typing import List
def plan_study_order(num_courses: int, requirements: List[List[int]]) -> List[int]:
unlocks = [[] for _ in range(num_courses)]
waiting = [0] * num_courses
for course, prereq in requirements:
unlocks[prereq].append(course)
waiting[course] += 1
queue = deque(c for c in range(num_courses) if waiting[c] == 0)
result = []
while queue:
current = queue.popleft()
result.append(current)
for nxt in unlocks[current]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
queue.append(nxt)
return result if len(result) == num_courses else []