KatInterview

Smallest Valid Sequence with Dependencies

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphheap

Last 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_items is not an integer in the valid range
  • dependencies is 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 <= 200000
  • 0 <= 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