Lexicographically Smallest Valid Task Schedule
Trees & GraphsAuto-graded · 23 test casesLast updated
Decide whether tasks with prerequisite constraints can all be run, and if so produce the lexicographically smallest valid run order, using topological sorting with a min-heap.
A build system has n jobs numbered 0 through n - 1. You are given a list dependencies of pairs [job, prereq]. Each pair means that prereq must be finished before job can start.
Write a function that decides whether every job can be run, and if so, returns the order in which to run them.
Task
Return a dictionary with exactly two keys:
"feasible":Trueif there is some ordering of allnjobs that satisfies every pair, otherwiseFalse."order": when feasible, the lexicographically smallest valid ordering of allnjobs, meaning the list that is smallest when compared element by element from the first position. When not feasible, an empty list[].
Because the smallest ordering is unique, there is exactly one correct answer for each input.
Rules and edge cases
- Duplicate pairs may appear. They express the same requirement and do not change the answer.
- A pair such as
[a, a](a job requiring itself) can never be satisfied, so the result is infeasible. - If
n = 0, the result is{"feasible": True, "order": []}. - Jobs with no constraints between them may appear in any relative position, as long as the final list is the lexicographically smallest valid one.
- All job labels in
dependenciesare valid, in the range0..n-1.
Constraints
0 <= n <= 10^50 <= len(dependencies) <= 2 * 10^5- Each pair is
[job, prereq]with0 <= job, prereq < n - Pairs may repeat
Examples
Example 1
Input: plan_task_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: {'feasible': True, 'order': [0, 1, 2, 3]}
Example 2
Input: plan_task_order(2, [[1, 0], [0, 1]])
Output: {'feasible': False, 'order': []}
Example 3
Input: plan_task_order(5, [[2, 1], [2, 0], [4, 3]])
Output: {'feasible': True, 'order': [0, 1, 2, 3, 4]}
Hints
Hint 1
Treat each requirement as a directed edge from the prerequisite to the job that needs it. All jobs can run exactly when this graph has no cycle.
Hint 2
Track how many unmet prerequisites each job has. Jobs with zero unmet prerequisites are ready to run, and finishing a job lowers the count for the jobs that depend on it.
Hint 3
To get the lexicographically smallest order, always run the smallest-numbered ready job next. A min-heap of ready jobs does this. Remove duplicate pairs (or account for them consistently) so counts stay correct, and if fewer than n jobs get scheduled, there is a cycle.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each pair [job, prereq] as a directed edge prereq -> job. All jobs can run if and only if this graph has no cycle, and a valid run order is a topological ordering.
- Build, for every job, the set of jobs that depend on it. Using sets removes duplicate pairs. For each distinct edge, increase the
unmetcounter of the dependent job. - Put every job whose
unmetcount is 0 into a min-heap of ready jobs. - Repeatedly pop the smallest ready job, append it to the order, and decrement
unmetfor each of its dependents. Any dependent that reaches 0 is pushed onto the heap. - If the order contains all
njobs, return it as feasible. Otherwise a cycle blocked some jobs, so return infeasible with an empty list.
Why it is correct
- Valid order: a job is only emitted when all its distinct prerequisites have already been emitted, so every constraint is respected.
- Cycle detection: a job on a cycle always has a predecessor on that cycle that is never emitted, so its counter never reaches 0. Conversely, if some jobs remain unemitted, each has an unemitted predecessor among the leftovers. Following predecessors in a finite set must repeat a job, which exposes a cycle. So all
njobs are emitted exactly when the graph is acyclic. - Lexicographically smallest: at every step the set of jobs that may legally go next is exactly the ready set. Choosing its smallest element gives the smallest possible value at this position, and choosing it never removes any option needed for a later position, since the remaining problem is the same kind of problem on the rest of the graph. By induction, greedy selection yields the lexicographically smallest valid order.
- Duplicates and self-loops: deduplication keeps the increments and decrements consistent. A self-loop
[a, a]makesawait on itself forever, so it is reported as infeasible.
Complexity
Let V = n and E = len(dependencies).
- Time:
O(E + V log V). Each edge is processed once, and each job is pushed to and popped from the heap once. - Space:
O(V + E)for the dependent sets, counters, heap and output.
Reference solution
import heapq
from typing import Dict, List
def plan_task_order(n: int, dependencies: List[List[int]]) -> Dict[str, object]:
dependents = [set() for _ in range(n)]
unmet = [0] * n
for job, prereq in dependencies:
if job not in dependents[prereq]:
dependents[prereq].add(job)
unmet[job] += 1
ready = [j for j in range(n) if unmet[j] == 0]
heapq.heapify(ready)
order = []
while ready:
cur = heapq.heappop(ready)
order.append(cur)
for nxt in dependents[cur]:
unmet[nxt] -= 1
if unmet[nxt] == 0:
heapq.heappush(ready, nxt)
if len(order) != n:
return {"feasible": False, "order": []}
return {"feasible": True, "order": order}