KatInterview

Unlock Order: Build a Dependency-Respecting Study Plan

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

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

  1. 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.
  2. For every course b, keep a list of the courses it unlocks. Build each list in the order the pairs appear in requirements.
  3. Create a first-in-first-out queue and add every course that has zero prerequisites, in increasing numeric order.
  4. 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.
  5. If the result contains all num_courses courses, 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 <= 2000
  • 0 <= len(requirements) <= num_courses * (num_courses - 1) / 2
  • Every pair in requirements is unique.
  • Every course number in a pair is in the range 0 to num_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.