Lexicographic Topological Sort of a Task Graph
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests directed graph construction, cycle detection via Kahn's algorithm, and deterministic tie-breaking with a min-heap to produce the lexicographically smallest valid ordering.
Pipeline Task Scheduler
You are building a scheduler for a data pipeline. Each pipeline consists of named tasks, and some tasks must complete before others can begin. Your job is to produce a valid execution order for all tasks.
You are given:
tasks: a list of unique task name strings.prereqs: a list of pairs[a, b], where each pair means taskamust finish before taskbstarts.
Return a list of all task names in a valid execution order — that is, for every pair [a, b] in prereqs, task a must appear somewhere before task b in the output.
Rules
- If the dependency graph contains a cycle (making it impossible to schedule all tasks), return an empty list
[]. - When more than one task is eligible to run at the same point, always pick the one that comes first alphabetically. Apply this rule at every step so the result is the lexicographically smallest valid order overall.
- Every task in
tasksmust appear in the output exactly once, unless a cycle is detected.
Constraints
1 <= len(tasks) <= 10000 <= len(prereqs) <= 5000- Task names contain only lowercase English letters and underscores, and are between 1 and 30 characters long.
- Every name that appears in
prereqsis guaranteed to also appear intasks. prereqsmay contain duplicate pairs; treat them as a single dependency.
Examples
Example 1
Input: schedule_tasks(['auth', 'risk_engine', 'order_routing', 'market_data'], [['auth', 'risk_engine'], ['auth', 'order_routing'], ['market_data', 'order_routing'], ['risk_engine', 'order_routing']])
Output: ['auth', 'market_data', 'risk_engine', 'order_routing']
Example 2
Input: schedule_tasks(['service_a', 'service_b'], [['service_a', 'service_b'], ['service_b', 'service_a']])
Output: []
Hints
Hint 1
Model the tasks as nodes in a directed graph where an edge from a to b means a must come before b. What property does a node have when all its predecessors have already been scheduled?
Hint 2
Kahn's algorithm processes nodes with in-degree zero. To enforce alphabetical tie-breaking at every step, think about which data structure always gives you the minimum element efficiently.
Hint 3
Duplicate edges in prereqs would inflate in-degree counts, causing nodes to wait for prerequisites that were already satisfied. Store neighbors in a set and only increment in-degree the first time you see each edge.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Framing the problem
Each task is a node in a directed graph. A pair [a, b] is a directed edge from a to b. A valid execution order is a topological sort of that graph. The alphabetical tie-breaking rule adds one constraint on top of the standard sort.
Algorithm: Kahn's with a min-heap
Kahn's algorithm works by repeatedly picking any node whose in-degree is zero (all predecessors already scheduled), appending it to the output, and decrementing the in-degree of its successors. Any successor that drops to zero becomes newly eligible.
Normally you would use a queue here. To satisfy the alphabetical requirement, swap the queue for a min-heap. heappop always returns the lexicographically smallest string currently in the heap, so the greedy choice at every step is automatic.
Step by step:
- Build an adjacency structure and compute each node's in-degree. Use a
setfor neighbors to absorb duplicate edges — without this, a duplicate[a, b]would incrementb's in-degree twice but only decrement it once, leavingbstranded. - Push every zero-in-degree task onto the min-heap.
- While the heap is non-empty, pop the smallest task, add it to the result, and push any successor whose in-degree just reached zero.
- After the loop, if the output length equals the number of distinct tasks, return it. Otherwise a cycle exists and no complete order is possible, so return
[].
Why the greedy choice is correct (exchange argument)
Any valid order must start with some zero-in-degree node. Swapping that node for the alphabetically smallest one cannot invalidate correctness (both are safe choices) and produces a smaller first element. The same argument applies after removing the chosen node, by induction, so the heap strategy yields the globally lexicographically smallest valid order.
Cycle detection
In a DAG, at least one node always has in-degree zero among the remaining nodes, so the heap never empties prematurely. In a graph with a cycle, every node on the cycle is waiting for its predecessor — none of them ever reach in-degree zero. They (and any nodes reachable only through them) are never emitted. Checking len(order) == len(nodes) therefore cleanly distinguishes the two cases with no extra pass.
Complexity
Let V = number of tasks, E = number of unique dependency pairs.
- Time: O(E + V log V) — graph construction is O(V + E); each node is pushed and popped from the heap once at O(log V); each edge is relaxed once.
- Space: O(V + E) — adjacency sets, in-degree map, heap, and output list.
Edge cases
- Duplicate pairs — absorbed by the neighbor
set; in-degree counts stay accurate. - Self-loop
[a, a]—agets in-degree 1 and is never freed; the function correctly returns[]. - No prerequisites — every task starts at in-degree 0; output is simply the tasks in sorted order.
- Disconnected components — all roots across all components land in the initial heap together and are processed normally.
- Cycle in one component only — the entire result is
[], because a partial order cannot be trusted when any part of the graph is unschedulable.
Reference solution
import heapq
from typing import List
def schedule_tasks(tasks: List[str], prereqs: List[List[str]]) -> List[str]:
nodes = set(tasks)
adjacency = {task: set() for task in nodes}
indegree = {task: 0 for task in nodes}
# Build graph, deduplicating edges so in-degrees stay accurate.
for before, after in prereqs:
if after not in adjacency[before]:
adjacency[before].add(after)
indegree[after] += 1
# Seed the heap with every task that has no prerequisites.
ready = [task for task in nodes if indegree[task] == 0]
heapq.heapify(ready)
order = []
while ready:
task = heapq.heappop(ready) # alphabetically smallest eligible task
order.append(task)
for successor in adjacency[task]:
indegree[successor] -= 1
if indegree[successor] == 0:
heapq.heappush(ready, successor)
# Any task never reaching in-degree 0 is part of (or blocked by) a cycle.
return order if len(order) == len(nodes) else []