KatInterview

Semester Planner: Build a Valid Course Sequence

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

Last updated

Produce a deterministic topological ordering of courses from prerequisite pairs, or an empty list when a circular requirement makes it impossible.

Semester Planner

A school offers course_count courses, numbered 0 through course_count - 1. You receive a list prereq_pairs, where each entry [a, b] means course b must be completed before course a can be taken.

Return a sequence containing every course exactly once, such that each course appears after all of its prerequisites. If the requirements contain a circular dependency, so that no such sequence exists, return an empty list.

Required output order

Several valid sequences may exist, but your function must return the one built by the following procedure, so that results are exactly reproducible:

  1. For every course, count how many entries in prereq_pairs name it as the first element a. Duplicate entries each count separately.
  2. Start a first-in-first-out queue holding every course whose count is 0, in increasing numeric order.
  3. Repeat while the queue is not empty:
    • Remove the course at the front and append it to the result.
    • Go through prereq_pairs in its given order. For each entry [a, b] where b is the course just removed, reduce the count of a by one. If that count becomes 0, add a to the back of the queue.
  4. If the result contains all course_count courses, return it. Otherwise return [].

A course that lists itself as its own prerequisite can never be taken, so the answer in that case is [].

Constraints

  • 1 <= course_count <= 2000
  • 0 <= len(prereq_pairs) <= 5000
  • Each entry of prereq_pairs has exactly two integers in the range [0, course_count - 1].
  • The same pair may appear more than once, and the requirement graph may be split into several disconnected parts.
  • Return [] if and only if the requirements contain a cycle (including a self-requirement).

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 b -> a, and track for every course how many prerequisites are still unmet.

Hint 2

Courses with zero unmet prerequisites can be taken right now. Take one, then lower the counter of every course that was waiting on it.

Hint 3

If you finish with fewer courses than course_count, the leftover ones are stuck behind a cycle, so return an empty list.