Resolve a Plan DAG into Parallel Waves
Problem Statement
Given a plan where each step declares which prior steps it depends on, group the steps into execution waves: each wave contains every step whose dependencies are all satisfied by earlier waves. This maximizes parallelism.
Background
This is a layered topological sort. Wave 0 is all steps with no dependencies. Wave w is all not-yet-scheduled steps whose deps are entirely within waves 0..w-1. Within a wave, step ids are sorted ascending. If a cycle prevents scheduling all steps, return "CYCLE".
Your Task
def plan_waves(steps):
- steps: list of {"id": int, "deps": [int, ...]}.
- Return a list of waves, each a sorted list of ids; or "CYCLE".
Input Format
- steps (list of dicts).
Output Format
- A list of lists of ints, or "CYCLE".
Sample
print(plan_waves([{"id":1,"deps":[]},{"id":2,"deps":[1]},{"id":3,"deps":[1]}]))
Output:
[[1], [2, 3]]
Example
print(plan_waves([{"id":1,"deps":[]},{"id":2,"deps":[1]},{"id":3,"deps":[1]}]))[[1], [2, 3]]
- Initialize the dependency map from the input: Step 1 has no dependencies (), while Steps 2 and 3 both depend on Step 1 (). The set of remaining unscheduled steps is and the set of scheduled steps is initially empty.
- Identify the first wave by finding all remaining steps whose dependencies are fully contained in the scheduled set. Only Step 1 qualifies because its dependency set is a subset of the empty scheduled set, resulting in Wave 0: .
- Update the state by adding Step 1 to the scheduled set and removing it from the remaining set, leaving for subsequent processing.
- Identify the second wave from the remaining steps. Both Step 2 and Step 3 have dependencies , which is now a subset of the scheduled set , so both are ready. Sorting their IDs yields Wave 1: .
- Update the state by adding Steps 2 and 3 to the scheduled set and removing them from the remaining set, which becomes empty, signaling the end of the process.
- The final output is
[[1], [2, 3]]
Constraints
- Wave 0: steps with no deps. Wave w: deps all scheduled in earlier waves.
- Sort ids ascending within each wave.
- Return
"CYCLE"if not all steps can be scheduled.