Smallest Valid Task Schedule with Prerequisites
Trees & GraphsAuto-graded · 23 test casesLast 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 meaningacomes beforeb.
Output
Either a list of all n task numbers in schedule order, or the string "IMPOSSIBLE".
Constraints
0 <= n <= 10^50 <= len(prereqs) <= 2 * 10^50 <= a, b < nfor 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each task as a graph node and each pair [a, b] as a directed edge a -> b. A valid schedule is a topological order of this graph, and one exists exactly when the graph has no cycle.
We use Kahn's algorithm with a min-heap in place of the usual queue:
- Build the successor lists and count, for each task, how many prerequisite edges point into it.
- Put every task with a count of zero into a min-heap. These are the tasks that can be scheduled right now.
- Repeatedly pop the smallest task from the heap and append it to the schedule. For each of its successors, decrease the count by one. When a count reaches zero, push that successor onto the heap.
- If the schedule has
ntasks at the end, return it. Otherwise some tasks never became ready, so there is a cycle and the answer is"IMPOSSIBLE".
Why it is correct
- Validity: a task enters the heap only after all of its prerequisites have been placed, so every pair
[a, b]ends up withabeforeb. - Cycle detection: a task on a cycle always waits for another task on that cycle, so its count never reaches zero and the schedule stays shorter than
n. In an acyclic graph, at least one unplaced task always has all its prerequisites placed, so the loop places every task. Self-pairs and duplicate pairs are handled naturally. A self-pair blocks the task forever, and duplicates are counted and decremented the same number of times. - Lexicographic minimality: take our schedule
Aand any other valid scheduleB, and look at the first position where they differ. Up to that point both have placed the same tasks, so the set of ready tasks is identical.Achose the minimum of that set, andBmust choose some member of it, soA's element is smaller. Choosing a small task never makes another ready task unavailable, so the greedy choice cannot hurt later positions.
Complexity
- Time:
O((n + m) log n), wherem = len(prereqs). Each task is pushed and popped once, and each edge is processed once. - Space:
O(n + m)for the successor lists, the counts, the heap and the output.
Reference solution
import heapq
from typing import List, Union
def smallest_schedule(n: int, prereqs: List[List[int]]) -> Union[List[int], str]:
successors = [[] for _ in range(n)]
waiting_on = [0] * n
for a, b in prereqs:
successors[a].append(b)
waiting_on[b] += 1
ready = [t for t in range(n) if waiting_on[t] == 0]
heapq.heapify(ready)
schedule = []
while ready:
task = heapq.heappop(ready)
schedule.append(task)
for nxt in successors[task]:
waiting_on[nxt] -= 1
if waiting_on[nxt] == 0:
heapq.heappush(ready, nxt)
return schedule if len(schedule) == n else "IMPOSSIBLE"