KatInterview

Smallest Job Schedule Under Dependency Rules

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

Last updated

Produce the lexicographically smallest topological ordering of a dependency graph, or an empty list if the dependencies contain a cycle.

Smallest Job Schedule Under Dependency Rules

A build system has n jobs numbered 0 to n - 1. You are given a list of rules, where each rule is a pair [a, b] meaning job a must finish before job b can start.

Return a schedule that runs every job exactly once and respects every rule.

  • If several schedules are valid, return the lexicographically smallest one. Compare two schedules position by position, and the first position where they differ decides: the schedule with the smaller job number there is smaller.
  • If no valid schedule exists because the rules form a cycle, return an empty list [].

Notes

  • Jobs that appear in no rule must still be included in the schedule.
  • A rule such as [a, a] is a cycle, so the answer is [].
  • The same rule may appear more than once. Duplicates do not change the answer.
  • If n = 0, return [].

Constraints

  • 0 <= n <= 10^5
  • 0 <= len(dependencies) <= 10^5
  • Each rule is a pair [a, b] with 0 <= a, b < n.
  • The return value is a list of n distinct integers, or [] if no valid schedule exists.

Examples

Example 1

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

Output: [0, 1, 2, 3]

Example 2

Input: schedule_jobs(2, [[0, 1], [1, 0]])

Output: []

Example 3

Input: schedule_jobs(3, [])

Output: [0, 1, 2]

Hints

Hint 1

Think of each rule as a directed edge a -> b. A job can run once all of its prerequisites are done, so track how many unfinished prerequisites each job has.

Hint 2

Start with the jobs that have zero unfinished prerequisites. Whenever you finish a job, reduce the count for each job that depends on it, and any job whose count reaches zero becomes available.

Hint 3

To get the lexicographically smallest result, always pick the smallest available job, which a min-heap does efficiently. If you end up scheduling fewer than n jobs, a cycle exists, so return an empty list.