KatInterview

Minimum Lexicographic Sequence with Precedence Constraints

Heaps, Sorting & SearchAuto-graded · 22 test cases
HardAuto-gradedHeaps, Sorting & Searchtopological-sortgraphheap

Last 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 (labeled 0 through n - 1)
  • constraints: a list of precedence pairs where constraints[i] = [x, y] means x must precede y

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 A is lexicographically smaller than sequence B when, at the first position where they differ, A contains a smaller number.
  • Circular dependencies (item x must precede y, y must precede z, and z must precede x) 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^5
  • 0 <= len(constraints) <= 2 * 10^5
  • Each constraint is a two-element list [x, y]
  • 0 <= x, y < n and x != 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.