Smallest Valid Sequence with Dependencies
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests topological sorting with lexicographic tie-breaking and cycle detection in a directed graph.
Smallest Valid Sequence with Dependencies
You are given total_items items numbered from 0 to total_items - 1. You are also given a list of dependency pairs where each pair [a, b] means item b must come before item a in any valid sequence.
Write a function that determines whether all items can be arranged in a valid order. If possible, return [True, order] where order is the lexicographically smallest valid sequence containing all item IDs. If the dependencies contain a cycle making a valid arrangement impossible, return [False, []].
Repeated dependency pairs should be treated as a single dependency.
Input Validation
Your function must raise ValueError if:
total_itemsis not an integer in the valid rangedependenciesis not iterable- Any dependency pair does not contain exactly two elements
- Any item ID in a pair is not an integer or is outside the range
[0, total_items)
Constraints
0 <= total_items <= 2000000 <= len(dependencies) <= 400000- A self-dependency
[a, a]forms a cycle - When
total_items == 0, return[True, []] - All inputs and outputs must be JSON-serializable
Examples
Example 1
Input: smallest_valid_sequence(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [True, [0, 1, 2, 3]]
Example 2
Input: smallest_valid_sequence(2, [[1, 0], [0, 1]])
Output: [False, []]
Example 3
Input: smallest_valid_sequence(3, [])
Output: [True, [0, 1, 2]]
Hints
Hint 1
Think about which items can be placed next at each step
Hint 2
When multiple items are ready to be placed, which one should you choose to get the smallest sequence?
Hint 3
A min-heap can help you always select the smallest available item
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires topological sorting with a specific constraint: among all valid orderings, we must produce the lexicographically smallest one. This means whenever multiple items are ready to be placed (all their dependencies satisfied), we must choose the smallest-numbered item.
We use Kahn's algorithm enhanced with a min-heap:
-
Build the dependency graph: Create an adjacency list where each item points to items that depend on it. Count incoming edges (unmet dependencies) for each item. Deduplicate edges to avoid inflating counts.
-
Initialize with zero-dependency items: All items with no incoming dependencies are ready immediately. Add them to a min-heap.
-
Process items in lexicographic order: Repeatedly extract the smallest ready item from the heap, add it to the result, and decrement the incoming count for its dependents. When a dependent's count reaches zero, add it to the heap.
-
Detect cycles: If we process fewer than
total_itemsitems, some remain blocked by a cycle. Return[False, []].
Why It Works
Correctness: An item enters the heap only when all its dependencies have been processed. Each prefix of the output therefore respects all constraints.
Cycle detection: Items in or downstream of a cycle never have all dependencies satisfied, so their incoming count never reaches zero. In an acyclic graph, at least one item is always available until all are processed.
Lexicographic minimality: At each step, we select the smallest available item. Suppose an optimal solution differs at position i, choosing item o where we chose smaller item g. Since g was also available and smaller, we could swap g to position i without violating constraints (no item between positions depends on g since it appeared later in that ordering). This produces a smaller sequence, contradicting optimality.
Complexity
Let V = total_items and E = number of distinct dependency pairs.
-
Time:
O((V + E) log V)- Graph construction and deduplication:
O(E)expected - Each item is pushed/popped from the heap once:
O(V log V) - Each edge is traversed once:
O(E)
- Graph construction and deduplication:
-
Space:
O(V + E)for the graph, incoming counts, deduplication set, heap, and output
Solution
import heapq
from typing import List
def smallest_valid_sequence(total_items: int, dependencies: List[List[int]]) -> List[object]:
if isinstance(total_items, bool) or not isinstance(total_items, int) or not (0 <= total_items <= 200000):
raise ValueError("total_items must be an integer in range")
try:
pairs = iter(dependencies)
except TypeError as exc:
raise ValueError("dependencies must be an iterable of pairs") from exc
graph = [[] for _ in range(total_items)]
incoming_count = [0] * total_items
seen_edges = set()
for pair in pairs:
if not isinstance(pair, (list, tuple)) or len(pair) != 2:
raise ValueError("each dependency must contain exactly two IDs")
item, required = pair
if (isinstance(item, bool) or not isinstance(item, int) or
isinstance(required, bool) or not isinstance(required, int) or
not (0 <= item < total_items) or not (0 <= required < total_items)):
raise ValueError("item IDs must be integers in range")
edge = (required, item)
if edge in seen_edges:
continue
seen_edges.add(edge)
graph[required].append(item)
incoming_count[item] += 1
ready = [item for item in range(total_items) if incoming_count[item] == 0]
heapq.heapify(ready)
result = []
while ready:
item = heapq.heappop(ready)
result.append(item)
for dependent in graph[item]:
incoming_count[dependent] -= 1
if incoming_count[dependent] == 0:
heapq.heappush(ready, dependent)
if len(result) != total_items:
return [False, []]
return [True, result]