KatInterview

Schedule Courses Under Prerequisite Rules

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphbfs

Last updated

Produce a deterministic course order that respects prerequisite pairs using a queue-based topological sort, or an empty list if the prerequisites contain a cycle.

A school offers num_courses courses, labeled 0 to num_courses - 1. Some courses have prerequisites, given as a list of pairs prereq_pairs. A pair [a, b] means course b must be finished before course a can be taken.

Return a full ordering of all courses in which every course appears after all of its prerequisites. If the prerequisites contain a cycle, so that no such ordering exists, return an empty list.

Required procedure

Many valid orderings can exist, so the output must be exactly the one produced by the following queue-based procedure:

  1. For each pair [a, b] in input order, record that finishing b unlocks a, and count one more unmet prerequisite for a. A repeated pair counts again each time it appears.
  2. Put every course with zero unmet prerequisites into a FIFO queue, in increasing label order.
  3. Repeat while the queue is not empty:
    • Remove the front course and append it to the result.
    • Go through the courses it unlocks in the order their pairs appeared in the input. For each one, reduce its unmet count by one. If the count becomes zero, add that course to the back of the queue.
  4. If the result contains all num_courses courses, return it. Otherwise return [].

The answer is all-or-nothing: if any course is stuck on or behind a cycle, return [] rather than a partial order. A pair like [a, a] is a cycle. If num_courses is 0, return [].

Constraints

  • 0 <= num_courses <= 10^5
  • 0 <= len(prereq_pairs) <= 2 * 10^5
  • Each pair has exactly two integers, each in [0, num_courses - 1].
  • Pairs may repeat, and the graph may be disconnected.
  • The solution should run in time roughly linear in num_courses + len(prereq_pairs).

Examples

Example 1

Input: plan_course_order(2, [[1, 0]])

Output: [0, 1]

Example 2

Input: plan_course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [0, 1, 2, 3]

Example 3

Input: plan_course_order(2, [[1, 0], [0, 1]])

Output: []

Hints

Hint 1

Treat each pair [a, b] as a directed edge from b to a. A valid schedule is a topological ordering of this graph.

Hint 2

Track how many prerequisites each course still lacks. Courses with zero are ready to take now, and finishing a course lowers the counts of the courses it unlocks.

Hint 3

Use a deque for the ready courses. If fewer than num_courses courses ever become ready, a cycle blocked the rest, so return an empty list.