Lexicographically Smallest Schedule or Detect a Deadlock
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests Kahn's algorithm with a min-heap to produce the lexicographically smallest valid processing order across nodes in a directed dependency graph, or detect a cycle.
Problem Description
You are managing a set of tasks numbered 0 through n-1. Some tasks have dependencies: a directed edge [a, b] means task a must complete before task b can begin. Given the number of tasks n and a list of dependency pairs deps, return a valid processing order for all tasks.
If completing all tasks is impossible because the dependencies form a circular chain, return an empty list instead.
Among all valid orderings, you must return the lexicographically smallest one. Concretely, whenever more than one task is available to run (all its prerequisites are done), always start the one with the lowest number first.
Duplicate entries in deps represent the same dependency and should be counted only once.
Constraints
1 <= n <= 10^40 <= len(deps) <= 10^5- Each element of
depsis a pair[a, b]with0 <= a, b < n - Duplicate pairs may appear and must be treated as a single dependency
- Self-dependencies like
[a, a]are valid input and constitute a cycle
Examples
Example 1
Input: get_deterministic_topo_order(3, [[0, 1], [0, 2]])
Output: [0, 1, 2]
Example 2
Input: get_deterministic_topo_order(4, [[0, 1], [1, 2], [2, 3]])
Output: [0, 1, 2, 3]
Example 3
Input: get_deterministic_topo_order(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Example 4
Input: get_deterministic_topo_order(5, [])
Output: [0, 1, 2, 3, 4]
Hints
Hint 1
Think about which tasks are runnable at any given moment: a task becomes runnable the instant every task it depends on has been scheduled. How would you track that count efficiently?
Hint 2
To always pick the lowest-numbered available task, consider a data structure that gives you the minimum element in better than linear time.
Hint 3
After processing all the tasks you can, compare how many you scheduled against n. What does a shortfall tell you about the structure of the remaining tasks?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
This is a topological sort problem with a tie-breaking rule. The standard algorithm for this is Kahn's algorithm, which works by repeatedly finding tasks with no remaining prerequisites and scheduling them. The twist here is that whenever multiple tasks are simultaneously eligible, we must always pick the one with the smallest label — producing the lexicographically smallest valid ordering overall.
Swapping the plain FIFO queue in textbook Kahn's for a min-heap enforces that rule at every step with no extra logic.
Step-by-step
-
Build the graph. Scan
depsand, for each unique pair[a, b], addbtoa's adjacency list and incrementb's prerequisite counter. Use a set to deduplicate: a repeated edge would inflate the counter and makebappear stuck in a cycle even when it isn't. -
Seed the heap. Collect every task whose prerequisite counter is already 0 and load them into a min-heap. These tasks have nothing blocking them and are all immediately schedulable.
-
Main loop.
- Pop the smallest task from the heap and append it to the schedule.
- For each task that depended on it, decrement that task's counter. If the counter hits 0, push it onto the heap — it is now unblocked.
- Repeat until the heap is empty.
-
Cycle check. If the schedule contains fewer than
ntasks, some tasks were never unblocked. That only happens when they sit inside (or depend on) a circular chain, so return[].
Why lexicographic minimality holds
At each step, the heap represents exactly the set of tasks that are legally schedulable right now. Picking anything other than the minimum produces a list that is larger at that position. Choosing the minimum never delays other tasks — removing a node from the graph can only add nodes to the ready set, never remove them. So the greedy choice is safe at every step, and by induction the full output is lexicographically smallest.
Why cycle detection is correct
If tasks c0 → c1 → … → ck → c0 form a cycle, every ci always has at least one unsatisfied prerequisite (the previous task in the cycle), so none ever enters the heap. They are simply left out of the schedule, making len(schedule) < n. Conversely, in a cycle-free graph (a DAG), there is always at least one task with no remaining prerequisites while tasks remain, so all n get scheduled.
Edge cases
- No dependencies: every task starts with counter 0, so the heap is seeded with all of them and outputs
[0, 1, …, n-1]. - Disconnected graph: the heap naturally mixes ready tasks from all components and always picks the global minimum.
- Self-loop
[a, a]: taskagets a counter of 1 that can never reach 0, so the output is[]. Correct, since a self-loop is a cycle. - Duplicate edges: the deduplication set ensures a repeated
[a, b]only counts once, preventing phantom deadlocks. n = 1: returns[0].
Complexity
- Time: O((n + m) log n), where m is the number of unique edges. Each task is pushed and popped from the heap at most once (O(n log n)), and each edge triggers at most one heap push (O(m log n)).
- Space: O(n + m) for the adjacency list, the deduplication set, the prerequisite counters, the heap, and the output.
Reference solution
import heapq
from typing import List
def get_deterministic_topo_order(n: int, deps: List[List[int]]) -> List[int]:
adjacency = [[] for _ in range(n)]
prereq_count = [0] * n
seen = set()
# Build the graph, deduplicating edges so counts stay accurate.
for a, b in deps:
if (a, b) in seen:
continue
seen.add((a, b))
adjacency[a].append(b)
prereq_count[b] += 1
# Seed the heap with every task that has no prerequisites.
ready = [i for i in range(n) if prereq_count[i] == 0]
heapq.heapify(ready)
schedule = []
while ready:
task = heapq.heappop(ready) # always pick the smallest available task
schedule.append(task)
for dependent in adjacency[task]:
prereq_count[dependent] -= 1
if prereq_count[dependent] == 0:
heapq.heappush(ready, dependent)
# A complete schedule has exactly n entries; anything less implies a cycle.
return schedule if len(schedule) == n else []