Schedule Tasks With Resource Unlock Dependencies
Trees & GraphsAuto-graded · 17 test casesLast 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 ofnstrings, whereproduces[i]is the name of the resource that taskiproduces upon completion (each task produces exactly one resource, and all produced resource names are unique).requires— a list ofnstrings orNonevalues, whererequires[i]is the name of the resource that taskineeds before it can begin, orNoneif taskihas 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 <= 2000produceshas exactlynstrings; each is a non-empty string of lowercase letters and digits, length ≤ 20.- All strings in
producesare distinct. requireshas exactlynentries; each is either a non-empty string orNone.- If
requires[i]is a non-empty string, it is guaranteed to appear somewhere inproduces(no dangling resource names). - A task will never require the resource it produces itself.
- There are no duplicate task IDs; task IDs are exactly
0throughn-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 [].
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Insight
Each requires[i] = r means there exists exactly one task u with produces[u] == r, and task u must complete before task i. This is precisely a directed edge u → i in a DAG (if the dependencies are cycle-free). The problem reduces to:
- Build the dependency graph.
- Find a topological ordering.
- Among all valid orderings, return the lexicographically smallest one.
Algorithm: Kahn's (BFS) with a Min-Heap
Step 1 — Build the graph.
- Create a dictionary
producer_ofmapping each resource name to its producer task ID. - For each task
vthat has a non-Nonerequirement, look upu = producer_of[requires[v]]and add edgeu → v, incrementingin_degree[v].
Step 2 — Kahn's algorithm.
- Push all tasks with
in_degree == 0into a min-heap (priority queue). - Repeatedly pop the smallest task
u, append it to the result, decrement the in-degree of each neighbour, and push any neighbour whose in-degree drops to 0.
Step 3 — Cycle detection.
- If the final ordering contains fewer than
ntasks, at least one cycle exists; return[].
Why lexicographically smallest?
At every step, multiple tasks may be "ready" (in-degree 0). A plain queue would give an arbitrary order; a min-heap ensures we always pick the smallest available ID, which greedily produces the lex-smallest valid permutation.
Correctness
Kahn's algorithm is a standard, correct topological sort. The greedy min-heap selection is correct for lex-smallest because: choosing the smallest available task at each step never blocks a smaller task that would otherwise be available sooner — any ready task can be placed here, and we pick the smallest, deferring larger ones.
Complexity
- Time: O(n log n) — each task is pushed/popped from the heap once (O(log n) each), and each edge is processed once.
- Space: O(n) for the graph, in-degree array, and heap.
import heapq
from typing import List, Optional
def schedule_tasks(n: int, produces: List[str], requires: List[Optional[str]]) -> List[int]:
# Map each resource name to the task that produces it
producer_of = {produces[i]: i for i in range(n)}
# Build adjacency list and in-degree count
adj = [[] for _ in range(n)]
in_degree = [0] * n
for v in range(n):
req = requires[v]
if req is not None:
u = producer_of[req]
adj[u].append(v)
in_degree[v] += 1
# Kahn's algorithm with a min-heap for lex-smallest ordering
heap = []
for i in range(n):
if in_degree[i] == 0:
heapq.heappush(heap, i)
order = []
while heap:
u = heapq.heappop(heap)
order.append(u)
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
heapq.heappush(heap, v)
if len(order) < n:
return []
return order