KatInterview

Smallest Valid Task Schedule with Prerequisites

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

Last updated

Produce the lexicographically smallest topological ordering of a directed graph, or report that no ordering exists because of a cycle.

Smallest Valid Task Schedule with Prerequisites

There are n tasks, numbered 0 to n - 1. You are also given a list of prerequisite pairs prereqs, where each entry [a, b] means task a must be scheduled somewhere before task b.

Build a schedule that contains every task exactly once and respects every prerequisite pair.

Rules

  • If several schedules are valid, return the lexicographically smallest one. Compare two schedules element by element from the front. At the first position where they differ, the schedule with the smaller task number is the smaller one.
  • If no valid schedule exists because the prerequisites contain a cycle, return the string "IMPOSSIBLE" (uppercase, no punctuation).
  • A single cycle anywhere in the graph makes the whole answer "IMPOSSIBLE", even if other tasks could be ordered. Never return a partial schedule.
  • If n = 0, return an empty list.
  • The same pair may appear more than once. A pair such as [3, 3], where a task must precede itself, is a cycle.

Input

  • n: the number of tasks.
  • prereqs: a list of [a, b] pairs, each meaning a comes before b.

Output

Either a list of all n task numbers in schedule order, or the string "IMPOSSIBLE".

Constraints

  • 0 <= n <= 10^5
  • 0 <= len(prereqs) <= 2 * 10^5
  • 0 <= a, b < n for every pair
  • Duplicate pairs and self-pairs may appear.

Examples

Example 1

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

Output: [0, 1, 2, 3]

Example 2

Input: smallest_schedule(3, [[0, 1], [1, 2], [2, 0]])

Output: 'IMPOSSIBLE'

Example 3

Input: smallest_schedule(5, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [3, 1, 2, 0, 4]

Hints

Hint 1

Think of each pair as a directed edge a -> b. A task can be placed once all of its prerequisites are already placed, which is when its in-degree reaches zero.

Hint 2

Repeatedly placing any ready task gives some valid order. To make it lexicographically smallest, which ready task should you pick at each step, and what data structure gives it to you quickly?

Hint 3

If you finish with fewer than n tasks placed, the leftover tasks lie on or behind a cycle. Duplicate edges are fine as long as you increment and decrement the in-degree once per occurrence.