KatInterview

Schedule Tasks With Resource Unlock Dependencies

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphstopological sortDAG

Last updated

Tests ability to apply topological ordering to determine a valid execution sequence of tasks where each task may unlock resources required by others.

Schedule Tasks With Resource Unlock Dependencies

You are building a task runner for a pipeline system. Each task has an integer ID from 0 to n-1. Some tasks produce a named resource when they complete, and some tasks require a named resource before they can start.

Formally, you are given:

  • n — the number of tasks.
  • produces — a list of n strings, where produces[i] is the name of the resource that task i produces upon completion (each task produces exactly one resource, and all produced resource names are unique).
  • requires — a list of n strings or None values, where requires[i] is the name of the resource that task i needs before it can begin, or None if task i has no prerequisite.

A task that requires resource r must be scheduled strictly after the task that produces r.

Your goal is to return a valid execution order of all n tasks as a list of task IDs such that no task starts before its required resource has been produced.

If no valid ordering exists (i.e., there is a cycle in the dependency graph), return an empty list [].

If multiple valid orderings exist, return the one that is lexicographically smallest (i.e., among all valid next choices at each step, always pick the task with the smallest ID).

Constraints

  • 1 <= n <= 2000
  • produces has exactly n strings; each is a non-empty string of lowercase letters and digits, length ≤ 20.
  • All strings in produces are distinct.
  • requires has exactly n entries; each is either a non-empty string or None.
  • If requires[i] is a non-empty string, it is guaranteed to appear somewhere in produces (no dangling resource names).
  • A task will never require the resource it produces itself.
  • There are no duplicate task IDs; task IDs are exactly 0 through n-1.

Examples

Example 1

Input: schedule_tasks(4, ['wood', 'nails', 'glue', 'paint'], [None, 'wood', 'wood', 'glue'])

Output: [0, 1, 2, 3]

Example 2

Input: schedule_tasks(3, ['alpha', 'beta', 'gamma'], ['gamma', 'alpha', 'beta'])

Output: []

Example 3

Input: schedule_tasks(5, ['e', 'd', 'c', 'b', 'a'], ['b', 'c', 'd', 'e', None])

Output: []

Hints

Hint 1

Build a directed graph where an edge u → v means task u must complete before task v. An edge exists when produces[u] == requires[v].

Hint 2

Use Kahn's algorithm (BFS-based topological sort) with a min-heap instead of a plain queue to always select the smallest available task ID next.

Hint 3

If the total number of tasks added to the result is less than n after the algorithm finishes, a cycle exists — return [].