Smallest-First Topological Ordering
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given n vertices numbered 0 through n - 1 and a collection of directed dependency pairs edges, where each entry [u, v] requires vertex u to appear before vertex v, compute a single topological ordering covering all n vertices.
Apply the following rules:
- Smallest-label tie-breaker: Whenever more than one vertex has zero unsatisfied incoming dependencies (in-degree
0), always pick the eligible vertex with the lowest integer label next. This rule applies globally across all vertices, including isolated vertices and separate connected components. - Cycle handling: If any directed cycle exists anywhere in the graph—making it impossible to schedule all
nvertices—return[]. - Repeated edges: Identical
[u, v]pairs may appear multiple times inedges; extra copies add no new constraint and must be ignored.
def get_deterministic_topo_order(n: int, edges: List[List[int]]) -> List[int]:
Examples
Example 1
- Input:
n = 4,edges = [[2, 0], [3, 1], [2, 0]] - Output:
[2, 0, 3, 1] - Explanation: The duplicate
[2, 0]edge is ignored. Initially, vertices2and3have no prerequisites;2 < 3, so2goes first. Placing2frees vertex0. Between the remaining ready vertices0and3,0 < 3goes next, followed by3, which finally frees1.
Example 2
- Input:
n = 5,edges = [[1, 3], [1, 4], [3, 0], [4, 0]] - Output:
[1, 2, 3, 4, 0] - Explanation: Vertices
1and2start with zero prerequisites (2is isolated). Picking1unlocks3and4, after which the ready pool{2, 3, 4}drains in numeric order2,3,4. Only once both3and4have been placed does vertex0become eligible at the end.
Example 3
- Input:
n = 4,edges = [[0, 2], [2, 3], [3, 1], [1, 2]] - Output:
[] - Explanation: Although vertex
0has no prerequisites, vertices2 -> 3 -> 1 -> 2form a directed loop, so no complete ordering of all4vertices exists.
Example 4
- Input:
n = 4,edges = [] - Output:
[0, 1, 2, 3] - Explanation: With zero dependencies, all four vertices start ready and are emitted in ascending numeric order.
Constraints
1 <= n <= 10^40 <= len(edges) <= 10^50 <= u, v < nfor each directed edge[u, v]inedgesedgesmay contain duplicate edges and self-loops.
Step-by-step walkthrough
Understand the goal and rules
We are given
nnodes labeled0throughn - 1and a list of directed edges[u, v](or(u, v)), where each edge meansumust appear beforevin the output schedule. We want to return a single list of allnnodes satisfying every edge, subject to three rules:- Deterministic tie-breaker: Whenever multiple nodes have zero remaining prerequisites, always select the node with the smallest numerical ID next.
- Cycle detection: If any cycle makes a valid ordering impossible, return
[]. - Duplicate edges: Repeated copies of the same
(u, v)edge add no new constraint and must be ignored.
Valid DAG: 2 ---> 0 Cycle: 0 ---> 2 ---> 3 3 ---> 1 ^ | | v Output: [2, 0, 3, 1] +----- 1 Output: [] (2, 3, 1 wait on one another)Why brute force and a FIFO queue both fall short
- Brute force is factorial: Checking every permutation of
[0, 1, ..., n - 1]in sorted order and returning the first valid schedule guarantees the smallest-first tie-breaker, but there aren!permutations — workable only up ton = 7or8, whereas herencan be10,000. - A plain first-in, first-out (FIFO) queue breaks ties by arrival time, not ID: Suppose nodes
2and3start ready,2unlocks0, and3unlocks1. A FIFO queue puts3ahead of0because3arrived earlier and outputs[2, 3, 0, 1], whereas0 < 3requires[2, 0, 3, 1].
We need a way to unlock nodes as prerequisites finish and always pick the smallest currently unlocked ID.
- Brute force is factorial: Checking every permutation of
Key idea: Kahn's algorithm with a min-heap
For each node
v, define its in-degree as the number of distinct prerequisitesu -> vthat have not been placed yet:- A node with
in_degree == 0is unlocked: nothing is waiting to go before it, so it can legally be placed next. - When we place an unlocked node
current, every outgoing edgecurrent -> neighboris satisfied, so we subtract1fromin_degree[neighbor]. Anyneighborwhosein_degreedrops to0becomes unlocked right then.
To enforce our tie-breaker, we store all currently unlocked nodes in a min-heap (
heapqin Python) — a priority queue that keeps the smallest number at the front soheapq.heappopalways removes the smallest available node ID inO(log n)time, even if it was unlocked later than larger waiting nodes.- A node with
Build the graph and ignore duplicate edges
We represent the graph with an adjacency list
neighbors[u](the list of distinct nodes directly unlocked byu) and an integer listin_degree[v]. To ignore duplicate edges cleanly, we record each(u, v)pair in aseen_edgesset before updatingneighborsorin_degree. Indexingedge[0]andedge[1]accepts both[u, v]lists and(u, v)tuples.Why must
neighborsandin_degreededuplicate together? If we skipped duplicates inneighborswithout skipping them inin_degree,in_degree[v]would stay positive forever (faking a cycle); if we skipped them inin_degreewithout skipping them inneighbors,uwould decrementin_degree[v]twice and unlockvbefore its other parents finished!neighbors: List[List[int]] = [[] for _ in range(n)] in_degree: List[int] = [0] * n seen_edges: Set[Tuple[int, int]] = set() for edge in edges: u = edge[0] v = edge[1] if (u, v) in seen_edges: continue seen_edges.add((u, v)) neighbors[u].append(v) in_degree[v] += 1Process unlocked nodes and detect cycles
First, scan
0 .. n - 1and push every node within_degree[node] == 0intoready_heap. Then loop whileready_heapis non-empty: pop the smallest ID, append it totopo_order, and decrementin_degreefor each of its outgoing neighbors, pushing any neighbor at the exact moment itsin_degreereaches0.How do we know whether the graph had a cycle? Every node on a cycle waits on the previous node in that cycle, so no node on a cycle (or downstream of a cycle) can ever reach
in_degree == 0. Therefore, checkinglen(topo_order) < nafter the heap empties catches every cycle — including self-loops[u, u]and cycles confined to one disconnected component — and returns[].ready_heap: List[int] = [] for node in range(n): if in_degree[node] == 0: heapq.heappush(ready_heap, node) topo_order: List[int] = [] while ready_heap: current = heapq.heappop(ready_heap) topo_order.append(current) for neighbor in neighbors[current]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: heapq.heappush(ready_heap, neighbor) if len(topo_order) < n: return []Trace Example 1 and Example 3
Example 1 — Priority tie-breaking and duplicate ignore:
n = 4,edges = [[2, 0], [3, 1], [2, 0]].Distinct edges: 2 ---> 0 3 ---> 1 (second [2, 0] ignored) Initial in_degree: [1, 1, 0, 0] (nodes 2 and 3 start unlocked) Step ready_heap Pop in_degree updates topo_order 1 [2, 3] 2 node 0: 1 -> 0 [2] 2 [0, 3] 0 (0 jumps ahead of 3) [2, 0] 3 [3] 3 node 1: 1 -> 0 [2, 0, 3] 4 [1] 1 (none) [2, 0, 3, 1]Notice Step 2: node
3enteredready_heapbefore node0, so a FIFO queue would output[2, 3, 0, 1]. The min-heap lets newly unlocked0jump ahead of3to produce[2, 0, 3, 1].Example 3 — Cycle detection:
n = 4,edges = [[0, 2], [2, 3], [3, 1], [1, 2]].Graph: 0 ---> 2 ---> 3 ---> 1 ---> 2 Initial in_degree: [0, 1, 2, 1] Pop 0 --> in_degree[2] drops 2 -> 1 (still blocked by 1!) ready_heap becomes [] --> len(topo_order) == 1 < 4 --> returns []Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def get_deterministic_topo_order(n: int, edges: List[List[int]]) -> List[int]: # neighbors[u]: list of distinct nodes v with a directed edge u -> v (u must come before v) neighbors: List[List[int]] = [[] for _ in range(n)] # in_degree[v]: number of distinct prerequisites still blocking node v in_degree: List[int] = [0] * n # seen_edges: set of (u, v) tuples so duplicate edges do not inflate in_degree seen_edges: Set[Tuple[int, int]] = set() # Phase 1: Build the adjacency list and count distinct incoming edges per node. for edge in edges: u = edge[0] v = edge[1] if (u, v) in seen_edges: continue seen_edges.add((u, v)) neighbors[u].append(v) in_degree[v] += 1 # Phase 2: Seed a min-heap with all nodes that initially have zero prerequisites. # ready_heap: min-heap of unlocked node IDs, e.g. [0, 3], so heappop picks the smallest ID. ready_heap: List[int] = [] for node in range(n): if in_degree[node] == 0: heapq.heappush(ready_heap, node) # Phase 3: Repeatedly place the smallest unlocked node and update its neighbors. topo_order: List[int] = [] while ready_heap: current = heapq.heappop(ready_heap) topo_order.append(current) for neighbor in neighbors[current]: in_degree[neighbor] -= 1 # Push neighbor only at the exact moment its final prerequisite finishes. if in_degree[neighbor] == 0: heapq.heappush(ready_heap, neighbor) # Phase 4: Any node on or behind a cycle never reaches in-degree 0, leaving topo_order short. if len(topo_order) < n: return [] return topo_order✅ Submit now — all tests should pass.
Intuition & how it works
Think of the n nodes as numbered college courses (0 through n - 1) and each directed edge u -> v as a rule saying "you must finish course u before taking course v." We want a topological order—a single left-to-right schedule of all n courses where every prerequisite appears before the course that depends on it—while always choosing the lowest-numbered eligible course whenever there is a choice, or returning [] if a cycle (a circular chain of prerequisites like 2 -> 3 -> 1 -> 2) makes finishing impossible.
Testing all n! permutations of [0, ..., n - 1] in sorted order would take factorial time, which is hopeless for n = 10,000. Using standard Kahn's algorithm—a method that tracks each node's in-degree (its count of unfinished incoming prerequisites) and repeatedly removes nodes with in-degree 0—with a plain first-in, first-out queue runs fast, but it processes courses in the order they became eligible rather than picking the smallest course number currently available.
Instead, we pair Kahn's algorithm with an adjacency list (an array neighbors where neighbors[u] lists every node directly unlocked by u) and a min-heap (a priority queue data structure that always pops the smallest number in O(log n) time). We also filter edges through a seen_edges set first so duplicate (u, v) rules never get counted twice.
Walk through n = 4 and edges = [[2, 0], [3, 1], [2, 0]]:
- Deduplicate edges to
2 -> 0and3 -> 1, givingin_degree = [1, 1, 0, 0]. Nodes2and3start with0prerequisites, soready_heap = [2, 3]. - Pop
2(the smallest in the heap) ->topo_order = [2]. Decrementin_degree[0]to0and push0, soready_heap = [0, 3]. - Pop
0(newly unlocked0jumps ahead of waiting3!) ->topo_order = [2, 0], leavingready_heap = [3]. - Pop
3->topo_order = [2, 0, 3], unlocking1, then pop1->[2, 0, 3, 1]. All4nodes were placed, confirming there is no cycle.
Complexity
Let V = n be the number of nodes and E = len(edges) be the number of input edges.
- Time:
O(E + V log V). Scanningedgeschecks and inserts each(u, v)tuple inseen_edgesinO(1)expected time (O(E)total). During Kahn's loop, each of theVnodes enters and leavesready_heapat most once atO(log V)per heap operation (O(V log V)total), and each unique edge decrements anin_degreeentry at most once (O(E)total). - Space:
O(V + E).in_degree,ready_heap, andtopo_ordereach hold up toVintegers, whileneighborsandseen_edgesstore at mostEunique directed edges.
Edge cases
- Graph with zero edges (
n = 4, edges = []): Every node starts within_degree == 0, so the min-heap pops[0, 1, 2, 3]. - Single node (
n = 1, edges = []): Immediately pops0and returns[0]. - Disconnected components: All components share a single
ready_heap, so nodes across components interleave globally by smallest ID rather than finishing one component before starting another. - Duplicate edges (
[[1, 0], [1, 0], [2, 0]]):seen_edgesignores the second[1, 0], soin_degree[0]is2(one for1, one for2) and0waits until both1and2are placed. - Self-loop (
[[1, 1]]): Node1gives itselfin_degree[1] = 1and can never unlock itself, solen(topo_order) < nreturns[]. - Partial cycle (
n = 4, edges = [[0, 2], [2, 3], [3, 1], [1, 2]]): Node0leaves the heap, while1,2, and3stay locked in their loop;len(topo_order) == 1 < 4cleanly returns[]instead of a partial list.
Common mistakes
- Using
collections.deque(FIFO queue) instead of a min-heap: Returns[2, 3, 0, 1]instead of[2, 0, 3, 1]onedges = [[2, 0], [3, 1]]because3was unlocked before0. - Sorting only the initial zero-in-degree nodes: Nodes unlocked mid-way still compete with nodes already waiting, so a one-time sort at the beginning is not enough.
- Mismatched duplicate handling between
neighborsandin_degree: Deduplicatingneighborswithout deduplicatingin_degreeleavesin_degree > 0forever (false cycle), while deduplicatingin_degreewithout deduplicatingneighborsdecrementsin_degreetwice from the same parent and unlocks a child before its other parents finish! - Returning
topo_orderwithout checkinglen(topo_order) == n: Without the length check, cyclic graphs silently return a subset of nodes instead of[].
Alternative approaches
- Counting all duplicate edges in both
neighborsandin_degree: Skippingseen_edgesand appending every copy of(u, v)while incrementingin_degree[v]by1per copy also works, because poppingudecrementsin_degree[v]the exact same number of times; however, deduplicating up front avoids redundant edge traversals and documents the problem's duplicate-edge rule explicitly. - Iterative three-color DFS: Useful when any topological sort (or printing an explicit cycle) is acceptable in
O(V + E)time, though it does not satisfy the smallest-available tie-breaker.
Follow-up questions
- What are the overall time and space bounds, and where does the priority queue add overhead compared to a standard queue? The algorithm runs in
O(E + V log V)time andO(V + E)space, whereV = nandE = len(edges). Replacing a FIFO queue (O(V + E)time) with a min-heap raises each vertex insertion and removal fromO(1)toO(log V); because edges only decrement integer counters inO(1)and push a vertex at most once when its counter hits zero, thelog Vfactor multipliesVrather thanE. - How would you adapt the algorithm if the tie-breaker required the lexicographically largest valid ordering instead? Lexicographical order compares two sequences left to right at the first index where they differ, so we want the largest legal vertex at index
0, then the largest legal vertex at index1, and so on. Removing any zero-in-degree vertex from an acyclic graph leaves the rest of the graph acyclic, so greedily popping from a max-heap (in Python'sheapq, push-nodeand negate-heapq.heappop(ready_heap)on pop) never gets stuck and produces the lexicographically largest topological ordering. Simply reversing the smallest ordering does not work—forn = 2with edge0 -> 1, the sole valid ordering is[0, 1], and reversing it to[1, 0]violates0 -> 1! - Could you implement topological sorting via Depth-First Search (DFS), and why is DFS awkward for enforcing this tie-breaking rule? Depth-First Search (DFS) (a traversal that plunges along outgoing edges before backtracking) colors vertices unvisited (
0), visiting (1), and visited (2), returning[]whenever an edge hits a visiting (1) vertex—a back edge (an arrow to an active ancestor, proving a cycle exists)—and reverses the post-order finish list (the order in which vertices finish exploring descendants) inO(V + E)time, using an explicit stack so chains of10^4vertices avoid Python's recursion limit. Although DFS yields a fixed output for a fixed neighbor order, post-order reversal cannot naturally enforce smallest-ready-first globally: onn = 3with edge0 -> 2, starting DFS over0, 1, 2finishes2then0then1and reverses to[1, 0, 2]instead of[0, 1, 2], making Kahn's algorithm with a min-heap the clean choice.
Follow-up questions
- What are the overall time and space bounds, and where does the priority queue add overhead compared to a standard queue?
- How would you adapt the algorithm if the tie-breaker required the lexicographically largest valid ordering instead?
- Could you implement topological sorting via Depth-First Search (DFS), and why is DFS awkward for enforcing this tie-breaking rule?
Similar questions
- Minesweeper Move Selection and Exact Risk Bot
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One