731. Schedule an agent's task plan into parallel waves with cycle detection
Planner agents often emit a task graph: each step lists the steps it needs. The executor must run independent steps in parallel, respect a concurrency limit, and refuse steps that can never run because of a cycle or a missing dependency, instead of hanging.
Write plan_waves(tasks, max_parallel). tasks is a dict: name -> list of dependency names.
- A task is blocked if any dependency is not a key in tasks, if it is on a cycle, or if it depends (directly or indirectly) on a blocked task.
- The other tasks run in waves. A task is ready when all its dependencies ran in EARLIER waves. Each wave takes the ready tasks in alphabetical order, at most max_parallel of them; ready tasks that do not fit wait for a later wave (still alphabetical with the newly ready ones).
Return (waves, blocked): waves is a list of lists of names, blocked is the sorted list of blocked names.
def plan_waves(tasks, max_parallel)Example 1
{"a": [], "b": ["a"], "c": ["a"], "d": ["b", "c"]}, max_parallel 1: waves [["a"], ["b"], ["c"], ["d"]], blocked [].
Example 2
Input: tasks = {'a': [], 'b': ['a'], 'c': ['a'], 'd': ['b', 'c']}, max_parallel = 4
Output: ([['a'], ['b', 'c'], ['d']], [])
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Run Kahn's algorithm with the cap.
Hint 2
Whatever is never scheduled once no task is ready is exactly the blocked set, as long as you never mark a task with an unknown dependency as ready.
Common mistakes
- The buggy version treats an unknown dependency as satisfied, so it happily runs a training step whose quota check never existed.
Understand the idea
A planner agent often outputs a task graph where each step lists the steps it needs first. The executor runs ready steps in parallel waves, but must refuse steps that can never run: ones that depend on a missing step, sit on a cycle, or depend on such a step.
tasks a: [], b: [], c: [a, b], d: [c], e: [x], f: [g], g: [f], max_parallel 2. e needs x, which does not exist, so e is blocked. f and g wait on each other, a cycle, so both are blocked. Wave 1: a and b are ready, take both. Wave 2: c. Wave 3: d. Result waves [[a, b], [c], [d]], blocked [e, f, g]. With max_parallel 1 the waves are [a], [b], [c], [d], because ready tasks that do not fit wait for the next wave and are re-sorted alphabetically with new arrivals.
first mark blocked tasks (missing dependency, then anything that cannot finish because of cycles or blocked dependencies), then repeatedly take up to max_parallel ready tasks in alphabetical order, where ready means every dependency ran in an earlier wave
Used in agent executors and build systems.