KatInterview

Lexicographically Smallest Valid Task Schedule

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

Last updated

Decide whether tasks with prerequisite constraints can all be run, and if so produce the lexicographically smallest valid run order, using topological sorting with a min-heap.

A build system has n jobs numbered 0 through n - 1. You are given a list dependencies of pairs [job, prereq]. Each pair means that prereq must be finished before job can start.

Write a function that decides whether every job can be run, and if so, returns the order in which to run them.

Task

Return a dictionary with exactly two keys:

  • "feasible": True if there is some ordering of all n jobs that satisfies every pair, otherwise False.
  • "order": when feasible, the lexicographically smallest valid ordering of all n jobs, meaning the list that is smallest when compared element by element from the first position. When not feasible, an empty list [].

Because the smallest ordering is unique, there is exactly one correct answer for each input.

Rules and edge cases

  • Duplicate pairs may appear. They express the same requirement and do not change the answer.
  • A pair such as [a, a] (a job requiring itself) can never be satisfied, so the result is infeasible.
  • If n = 0, the result is {"feasible": True, "order": []}.
  • Jobs with no constraints between them may appear in any relative position, as long as the final list is the lexicographically smallest valid one.
  • All job labels in dependencies are valid, in the range 0..n-1.

Constraints

  • 0 <= n <= 10^5
  • 0 <= len(dependencies) <= 2 * 10^5
  • Each pair is [job, prereq] with 0 <= job, prereq < n
  • Pairs may repeat

Examples

Example 1

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

Output: {'feasible': True, 'order': [0, 1, 2, 3]}

Example 2

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

Output: {'feasible': False, 'order': []}

Example 3

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

Output: {'feasible': True, 'order': [0, 1, 2, 3, 4]}

Hints

Hint 1

Treat each requirement as a directed edge from the prerequisite to the job that needs it. All jobs can run exactly when this graph has no cycle.

Hint 2

Track how many unmet prerequisites each job has. Jobs with zero unmet prerequisites are ready to run, and finishing a job lowers the count for the jobs that depend on it.

Hint 3

To get the lexicographically smallest order, always run the smallest-numbered ready job next. A min-heap of ready jobs does this. Remove duplicate pairs (or account for them consistently) so counts stay correct, and if fewer than n jobs get scheduled, there is a cycle.