Build Order with Parallel Execution - Problem

Given a set of build tasks with their dependencies, find the minimum number of parallel build rounds needed and output which tasks can be executed in each round.

Each task has a list of dependencies that must be completed before it can start. Tasks with no dependencies can run in the first round. Once a round completes, tasks whose dependencies are now satisfied can run in the next round.

Input:

  • An array of task names
  • An array of dependency pairs [task, dependency] where task depends on dependency

Output:

  • A 2D array where each sub-array contains tasks that can run in parallel in that round

Note: If there's a circular dependency, return an empty array.

Input & Output

Example 1 — Basic Dependencies
$ Input: tasks = ["A","B","C","D","E","F"], dependencies = [["C","A"],["D","B"],["E","C"],["F","D"]]
Output: [["A","B"],["C","D"],["E","F"]]
💡 Note: Round 1: A and B have no dependencies. Round 2: C needs A, D needs B. Round 3: E needs C, F needs D.
Example 2 — No Dependencies
$ Input: tasks = ["X","Y","Z"], dependencies = []
Output: [["X","Y","Z"]]
💡 Note: All tasks have no dependencies, so they can all run in parallel in round 1.
Example 3 — Linear Chain
$ Input: tasks = ["P","Q","R"], dependencies = [["Q","P"],["R","Q"]]
Output: [["P"],["Q"],["R"]]
💡 Note: Sequential dependencies: P → Q → R, so each runs in a separate round.

Constraints

  • 1 ≤ tasks.length ≤ 1000
  • 0 ≤ dependencies.length ≤ 5000
  • Each task name is a unique string
  • Dependencies form a valid DAG (no self-loops allowed)

Visualization

Tap to expand
Build Order with Parallel ExecutionINPUT: Task DependenciesABCDDependencies: C→A, D→BTasks: [A,B,C,D,E,F]ALGORITHM: Kahn's Method1Calculate In-DegreesCount dependencies per task2Process Zero In-DegreeAdd ready tasks to current round3Update DependenciesReduce in-degree of dependent tasks4Repeat Until DoneContinue until all tasks scheduledRESULT: Parallel RoundsRound 1:[A, B]Round 2:[C, D]2 rounds vs 4 sequential50% faster executionKey Insight:Track in-degree (dependency count) for each task - when it reaches zero, the task is ready for parallel execution.TutorialsPoint - Build Order with Parallel Execution | Kahn's Algorithm
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.5K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen