PIXELBANKv9.1.0
Menu

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:

Input:
print(plan_waves([{"id":1,"deps":[]},{"id":2,"deps":[1]},{"id":3,"deps":[1]}]))
Output:
[[1], [2, 3]]
Reasoning:
  • Initialize the dependency map from the input: Step 1 has no dependencies (∅\emptyset), while Steps 2 and 3 both depend on Step 1 ({1}\{1\}). The set of remaining unscheduled steps is {1,2,3}\{1, 2, 3\} 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 ∅\emptyset is a subset of the empty scheduled set, resulting in Wave 0: [1][1].
  • Update the state by adding Step 1 to the scheduled set {1}\{1\} and removing it from the remaining set, leaving {2,3}\{2, 3\} for subsequent processing.
  • Identify the second wave from the remaining steps. Both Step 2 and Step 3 have dependencies {1}\{1\}, which is now a subset of the scheduled set {1}\{1\}, so both are ready. Sorting their IDs yields Wave 1: [2,3][2, 3].
  • 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.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.