Smallest-ID Study Order for One Goal Course
Trees & GraphsAuto-graded · 21 test casesLast updated
Restrict a dependency graph to the ancestors of one goal node, then produce the smallest-ID-first topological order, or an empty list if a cycle blocks it.
A school offers num_courses courses, numbered 0 to num_courses - 1. Dependencies are given as a list of pairs requirements. A pair [x, y] means course y must be completed before course x can be started.
A student only cares about one course, goal. Build a study order that contains goal and every course it needs, either directly or through a chain of other requirements. No other course may appear in the order.
The order must follow these rules:
- Only what is needed. Include
goaland all of its direct and indirect prerequisites. Leave out every other course. - Cycles that matter. If the courses needed for
goalcontain a circular dependency (including a course that requires itself, such as[t, t]), no valid order exists, so return an empty list[]. Circular dependencies among courses that are not needed forgoalhave no effect on the answer. - Repeated pairs. The same pair may appear more than once in
requirements. Repeats count as a single dependency. - Tie-breaking. Build the order one course at a time. Whenever several courses could be taken next (all their needed prerequisites are already in the order), choose the one with the smallest course number.
Return the resulting list of course numbers in the order they should be taken.
Constraints
1 <= num_courses <= 10^50 <= len(requirements) <= 2 * 10^5len(requirements[i]) == 20 <= x, y < num_coursesfor every pair[x, y]0 <= goal < num_courses
Examples
Example 1
Input: build_goal_study_order(6, [[1, 0], [2, 0], [3, 1], [3, 2], [4, 5], [5, 4]], 3)
Output: [0, 1, 2, 3]
Example 2
Input: build_goal_study_order(4, [[1, 0], [2, 1], [0, 2]], 2)
Output: []
Example 3
Input: build_goal_study_order(3, [], 1)
Output: [1]
Hints
Hint 1
Edges go from prerequisite to dependent. To find which courses matter, walk the edges in the reverse direction starting from the goal course.
Hint 2
Once you have the set of needed courses, run a topological sort (Kahn's algorithm) on only that set. Every prerequisite of a needed course is itself needed, so its in-degree counts only needed courses.
Hint 3
Use a min-heap instead of a plain queue so the smallest available course number is always taken next. Store prerequisites in sets so duplicate pairs are not double counted, and compare the output length with the size of the needed set to detect a cycle.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two stages.
-
Find the needed courses. Store, for each course, the set of its direct prerequisites. Using sets removes duplicate pairs automatically. Starting from
goal, run an iterative DFS over these prerequisite sets. Every course reached is needed, and the visited set is exactlygoalplus all of its direct and indirect prerequisites. -
Order them. Run Kahn's topological sort on only the needed courses. Use a min-heap for the ready courses so the smallest course number is always taken first. If the sort ends with fewer courses than the needed set contains, some courses sit on or behind a cycle, so return
[].
Why it is correct
- Closure. Every prerequisite of a needed course was added during the traversal, so no needed course has an incoming dependency from outside the needed set. Its full in-degree (the size of its prerequisite set) therefore equals its in-degree inside the subgraph, and no recomputation is needed.
- Duplicates. Because prerequisites are stored in sets, a repeated pair adds just one dependency. Otherwise the in-degree would be too high and a false cycle would be reported.
- Cycle scoping. Cycles among unneeded courses are never visited, so they cannot affect the result. A cycle among needed courses (or a self-requirement) keeps its courses from ever reaching in-degree 0, so the output is shorter than the needed set and we return
[]. - Tie-breaking. At every step the heap holds exactly the needed courses whose prerequisites are all placed. Popping the minimum applies the "smallest course number first" rule, which gives the lexicographically smallest valid order.
- Deep chains. The traversal uses an explicit stack, so chains of about 10^5 courses do not hit Python's recursion limit.
Complexity
Let V = num_courses, E = len(requirements), and R and E_R be the number of needed courses and the edges among them.
- Time: O(V + E + E_R + R log R). Building the sets costs O(V + E), the traversal and unlock lists cost O(R + E_R), and each needed course is pushed to and popped from the heap once.
- Space: O(V + E).
Reference solution
import heapq
from typing import List
def build_goal_study_order(num_courses: int, requirements: List[List[int]], goal: int) -> List[int]:
# needs[c] = set of courses that must come before c (duplicates collapse).
needs = [set() for _ in range(num_courses)]
for course, prereq in requirements:
needs[course].add(prereq)
# Collect goal and all of its transitive prerequisites (iterative DFS).
needed = {goal}
stack = [goal]
while stack:
course = stack.pop()
for prereq in needs[course]:
if prereq not in needed:
needed.add(prereq)
stack.append(prereq)
# The needed set is closed under prerequisites, so full in-degree
# equals in-degree inside the needed subgraph.
indegree = {c: len(needs[c]) for c in needed}
unlocks = {c: [] for c in needed}
for c in needed:
for prereq in needs[c]:
unlocks[prereq].append(c)
# Kahn's algorithm with a min-heap for smallest-ID-first ordering.
ready = [c for c in needed if indegree[c] == 0]
heapq.heapify(ready)
order = []
while ready:
course = heapq.heappop(ready)
order.append(course)
for nxt in unlocks[course]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
heapq.heappush(ready, nxt)
if len(order) != len(needed):
return []
return order