KatInterview

Smallest-ID Study Order for One Goal Course

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphheap

Last 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:

  1. Only what is needed. Include goal and all of its direct and indirect prerequisites. Leave out every other course.
  2. Cycles that matter. If the courses needed for goal contain 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 for goal have no effect on the answer.
  3. Repeated pairs. The same pair may appear more than once in requirements. Repeats count as a single dependency.
  4. 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^5
  • 0 <= len(requirements) <= 2 * 10^5
  • len(requirements[i]) == 2
  • 0 <= x, y < num_courses for 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.