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 n vertices—return [].
  • Repeated edges: Identical [u, v] pairs may appear multiple times in edges; 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, vertices 2 and 3 have no prerequisites; 2 < 3, so 2 goes first. Placing 2 frees vertex 0. Between the remaining ready vertices 0 and 3, 0 < 3 goes next, followed by 3, which finally frees 1.

Example 2

  • Input: n = 5, edges = [[1, 3], [1, 4], [3, 0], [4, 0]]
  • Output: [1, 2, 3, 4, 0]
  • Explanation: Vertices 1 and 2 start with zero prerequisites (2 is isolated). Picking 1 unlocks 3 and 4, after which the ready pool {2, 3, 4} drains in numeric order 2, 3, 4. Only once both 3 and 4 have been placed does vertex 0 become eligible at the end.

Example 3

  • Input: n = 4, edges = [[0, 2], [2, 3], [3, 1], [1, 2]]
  • Output: []
  • Explanation: Although vertex 0 has no prerequisites, vertices 2 -> 3 -> 1 -> 2 form a directed loop, so no complete ordering of all 4 vertices 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^4
  • 0 <= len(edges) <= 10^5
  • 0 <= u, v < n for each directed edge [u, v] in edges
  • edges may contain duplicate edges and self-loops.

Step-by-step walkthrough

  1. Understand the goal and rules

    We are given n nodes labeled 0 through n - 1 and a list of directed edges [u, v] (or (u, v)), where each edge means u must appear before v in the output schedule. We want to return a single list of all n nodes 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)
    
  2. 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 are n! permutations — workable only up to n = 7 or 8, whereas here n can be 10,000.
    • A plain first-in, first-out (FIFO) queue breaks ties by arrival time, not ID: Suppose nodes 2 and 3 start ready, 2 unlocks 0, and 3 unlocks 1. A FIFO queue puts 3 ahead of 0 because 3 arrived earlier and outputs [2, 3, 0, 1], whereas 0 < 3 requires [2, 0, 3, 1].

    We need a way to unlock nodes as prerequisites finish and always pick the smallest currently unlocked ID.

  3. Key idea: Kahn's algorithm with a min-heap

    For each node v, define its in-degree as the number of distinct prerequisites u -> v that have not been placed yet:

    • A node with in_degree == 0 is unlocked: nothing is waiting to go before it, so it can legally be placed next.
    • When we place an unlocked node current, every outgoing edge current -> neighbor is satisfied, so we subtract 1 from in_degree[neighbor]. Any neighbor whose in_degree drops to 0 becomes unlocked right then.

    To enforce our tie-breaker, we store all currently unlocked nodes in a min-heap (heapq in Python) — a priority queue that keeps the smallest number at the front so heapq.heappop always removes the smallest available node ID in O(log n) time, even if it was unlocked later than larger waiting nodes.

  4. Build the graph and ignore duplicate edges

    We represent the graph with an adjacency list neighbors[u] (the list of distinct nodes directly unlocked by u) and an integer list in_degree[v]. To ignore duplicate edges cleanly, we record each (u, v) pair in a seen_edges set before updating neighbors or in_degree. Indexing edge[0] and edge[1] accepts both [u, v] lists and (u, v) tuples.

    Why must neighbors and in_degree deduplicate together? If we skipped duplicates in neighbors without skipping them in in_degree, in_degree[v] would stay positive forever (faking a cycle); if we skipped them in in_degree without skipping them in neighbors, u would decrement in_degree[v] twice and unlock v before 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] += 1
    
  5. Process unlocked nodes and detect cycles

    First, scan 0 .. n - 1 and push every node with in_degree[node] == 0 into ready_heap. Then loop while ready_heap is non-empty: pop the smallest ID, append it to topo_order, and decrement in_degree for each of its outgoing neighbors, pushing any neighbor at the exact moment its in_degree reaches 0.

    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, checking len(topo_order) < n after 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 []
    
  6. 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 3 entered ready_heap before node 0, so a FIFO queue would output [2, 3, 0, 1]. The min-heap lets newly unlocked 0 jump ahead of 3 to 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 []
    
  7. 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]]:

  1. Deduplicate edges to 2 -> 0 and 3 -> 1, giving in_degree = [1, 1, 0, 0]. Nodes 2 and 3 start with 0 prerequisites, so ready_heap = [2, 3].
  2. Pop 2 (the smallest in the heap) -> topo_order = [2]. Decrement in_degree[0] to 0 and push 0, so ready_heap = [0, 3].
  3. Pop 0 (newly unlocked 0 jumps ahead of waiting 3!) -> topo_order = [2, 0], leaving ready_heap = [3].
  4. Pop 3 -> topo_order = [2, 0, 3], unlocking 1, then pop 1 -> [2, 0, 3, 1]. All 4 nodes 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). Scanning edges checks and inserts each (u, v) tuple in seen_edges in O(1) expected time (O(E) total). During Kahn's loop, each of the V nodes enters and leaves ready_heap at most once at O(log V) per heap operation (O(V log V) total), and each unique edge decrements an in_degree entry at most once (O(E) total).
  • Space: O(V + E). in_degree, ready_heap, and topo_order each hold up to V integers, while neighbors and seen_edges store at most E unique directed edges.

Edge cases

  • Graph with zero edges (n = 4, edges = []): Every node starts with in_degree == 0, so the min-heap pops [0, 1, 2, 3].
  • Single node (n = 1, edges = []): Immediately pops 0 and 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_edges ignores the second [1, 0], so in_degree[0] is 2 (one for 1, one for 2) and 0 waits until both 1 and 2 are placed.
  • Self-loop ([[1, 1]]): Node 1 gives itself in_degree[1] = 1 and can never unlock itself, so len(topo_order) < n returns [].
  • Partial cycle (n = 4, edges = [[0, 2], [2, 3], [3, 1], [1, 2]]): Node 0 leaves the heap, while 1, 2, and 3 stay locked in their loop; len(topo_order) == 1 < 4 cleanly 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] on edges = [[2, 0], [3, 1]] because 3 was unlocked before 0.
  • 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 neighbors and in_degree: Deduplicating neighbors without deduplicating in_degree leaves in_degree > 0 forever (false cycle), while deduplicating in_degree without deduplicating neighbors decrements in_degree twice from the same parent and unlocks a child before its other parents finish!
  • Returning topo_order without checking len(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 neighbors and in_degree: Skipping seen_edges and appending every copy of (u, v) while incrementing in_degree[v] by 1 per copy also works, because popping u decrements in_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 and O(V + E) space, where V = n and E = len(edges). Replacing a FIFO queue (O(V + E) time) with a min-heap raises each vertex insertion and removal from O(1) to O(log V); because edges only decrement integer counters in O(1) and push a vertex at most once when its counter hits zero, the log V factor multiplies V rather than E.
  • 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 index 1, 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's heapq, push -node and 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—for n = 2 with edge 0 -> 1, the sole valid ordering is [0, 1], and reversing it to [1, 0] violates 0 -> 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) in O(V + E) time, using an explicit stack so chains of 10^4 vertices 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: on n = 3 with edge 0 -> 2, starting DFS over 0, 1, 2 finishes 2 then 0 then 1 and reverses to [1, 0, 2] instead of [0, 1, 2], making Kahn's algorithm with a min-heap the clean choice.

Follow-up questions

Similar questions

More Runloop interview questions

All 2 Runloop questions →