KatInterview

Lexicographically Smallest Schedule or Detect a Deadlock

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

Last updated

Tests Kahn's algorithm with a min-heap to produce the lexicographically smallest valid processing order across nodes in a directed dependency graph, or detect a cycle.

Problem Description

You are managing a set of tasks numbered 0 through n-1. Some tasks have dependencies: a directed edge [a, b] means task a must complete before task b can begin. Given the number of tasks n and a list of dependency pairs deps, return a valid processing order for all tasks.

If completing all tasks is impossible because the dependencies form a circular chain, return an empty list instead.

Among all valid orderings, you must return the lexicographically smallest one. Concretely, whenever more than one task is available to run (all its prerequisites are done), always start the one with the lowest number first.

Duplicate entries in deps represent the same dependency and should be counted only once.

Constraints

  • 1 <= n <= 10^4
  • 0 <= len(deps) <= 10^5
  • Each element of deps is a pair [a, b] with 0 <= a, b < n
  • Duplicate pairs may appear and must be treated as a single dependency
  • Self-dependencies like [a, a] are valid input and constitute a cycle

Examples

Example 1

Input: get_deterministic_topo_order(3, [[0, 1], [0, 2]])

Output: [0, 1, 2]

Example 2

Input: get_deterministic_topo_order(4, [[0, 1], [1, 2], [2, 3]])

Output: [0, 1, 2, 3]

Example 3

Input: get_deterministic_topo_order(3, [[0, 1], [1, 2], [2, 0]])

Output: []

Example 4

Input: get_deterministic_topo_order(5, [])

Output: [0, 1, 2, 3, 4]

Hints

Hint 1

Think about which tasks are runnable at any given moment: a task becomes runnable the instant every task it depends on has been scheduled. How would you track that count efficiently?

Hint 2

To always pick the lowest-numbered available task, consider a data structure that gives you the minimum element in better than linear time.

Hint 3

After processing all the tasks you can, compare how many you scheduled against n. What does a shortfall tell you about the structure of the remaining tasks?