Minimum Lexicographic Sequence with Precedence Constraints
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Find the smallest valid ordering of numbered items when some must precede others, or detect when circular dependencies make ordering impossible.
You have n items numbered from 0 to n - 1 that must be arranged in a sequence. Certain items have precedence constraints: a constraint [x, y] means item x must appear somewhere before item y in the final sequence.
Write a function that produces a valid arrangement respecting all constraints. When multiple valid arrangements exist, return the one that is lexicographically smallest. If circular dependencies prevent any valid arrangement, return an empty list.
Function Signature
def min_precedence_order(n: int, constraints: List[List[int]]) -> List[int]:
Parameters
n: the total count of items (labeled0throughn - 1)constraints: a list of precedence pairs whereconstraints[i] = [x, y]meansxmust precedey
Output
A list containing all integers from 0 to n - 1 in an order that satisfies every constraint, choosing the lexicographically smallest such order. Return [] if no valid order exists.
Rules
- A valid sequence includes each item exactly once and respects every precedence constraint.
- Sequence
Ais lexicographically smaller than sequenceBwhen, at the first position where they differ,Acontains a smaller number. - Circular dependencies (item
xmust precedey,ymust precedez, andzmust precedex) make ordering impossible. - The same constraint pair may appear multiple times in the input; treat duplicates as expressing the same requirement.
Constraints
1 <= n <= 10^50 <= len(constraints) <= 2 * 10^5- Each constraint is a two-element list
[x, y] 0 <= x, y < nandx != y
Examples
Example 1
Input: min_precedence_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [3, 1, 2, 0]
Example 2
Input: min_precedence_order(3, [[2, 0]])
Output: [1, 2, 0]
Example 3
Input: min_precedence_order(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Hints
Hint 1
Think about which items can be placed first in the sequence—what property must they have?
Hint 2
Use a min-heap to always select the smallest available item that can legally be placed next.
Hint 3
Track how many unsatisfied predecessors each item has; an item becomes available when this count reaches zero.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires topological sorting with a twist: among all valid orderings, we need the lexicographically smallest one.
The core insight is that at any point during construction, the next item we place must be chosen from those that have all their predecessors already placed. An item is "available" when every constraint requiring something to come before it has been satisfied.
To achieve lexicographic minimality, we use a greedy strategy with a min-heap:
- Build a directed graph where an edge from
xtoyrepresents the constraint thatxmust precedey - Count how many unsatisfied predecessors each item has (its "in-degree")
- Place all items with zero predecessors into a min-heap
- Repeatedly extract the smallest available item, add it to the result, and decrease the in-degree of items depending on it
- When an item's in-degree reaches zero, it becomes available and enters the heap
- If we successfully place all
nitems, we have a valid order; otherwise, circular dependencies prevented completion
Why This Works
Correctness: An item enters the result only after all its predecessors have been placed (its in-degree reached zero), guaranteeing constraint satisfaction.
Lexicographic Optimality: At each step, the set of available items represents all legal choices for the next position. In a directed acyclic graph, selecting any available item can always be extended to a complete ordering (removing a node from a DAG leaves a DAG). Therefore, greedily choosing the smallest available item at each step produces the lexicographically smallest sequence. Any other valid ordering that differs at position i must have chosen a larger item when a smaller one was available, making it lexicographically larger.
Cycle Detection: Items involved in circular dependencies never reach zero in-degree because they perpetually wait for each other. When the algorithm completes with fewer than n items placed, we know a cycle exists.
Complexity
Let m = len(constraints).
- Time:
O(n + m)to build the graph. Each item is inserted into and removed from the heap once, contributingO(n log n). Each constraint edge is processed once during the relaxation phase, contributingO(m). Total:O(n log n + m). - Space:
O(n + m)for the adjacency lists, in-degree counts, heap, and output sequence.
Implementation
import heapq
from typing import List
def min_precedence_order(n: int, constraints: List[List[int]]) -> List[int]:
# Build directed graph and count incoming edges for each item
graph = [[] for _ in range(n)]
incoming = [0] * n
for x, y in constraints:
graph[x].append(y)
incoming[y] += 1
# Start with all items that have no predecessors
available = [item for item in range(n) if incoming[item] == 0]
heapq.heapify(available)
result = []
while available:
# Always pick the smallest available item
current = heapq.heappop(available)
result.append(current)
# Mark this item as placed; may unlock items that depend on it
for dependent in graph[current]:
incoming[dependent] -= 1
if incoming[dependent] == 0:
heapq.heappush(available, dependent)
# If we placed all items, we found a valid order
return result if len(result) == n else []