← Questions

Find bottleneck dependencies in a parallel build

0

A coding interview question asked at Databricks and Meta. It tests graphs, topological sort and bfs.

You are given n build targets numbered 0 to n - 1 and a list of directed edges edges. An edge [u, v] means target v cannot start building until target u has finished. The graph has no cycles.

The build runs on a clock with unlimited parallel builders:

  • Every target takes exactly one time step to build.
  • A target starts in the first time step after all of its prerequisites have finished. Targets with no prerequisites build in step 1.
  • Any number of targets can build in the same step.

A target is a bottleneck if it is the only target building during its time step.

Implement:

def find_bottlenecks(n: int, edges: list[tuple[int, int]]) -> list[int]:
    ...

Return the bottleneck targets in the order they are built. If the input contains a cycle, raise an error.

Constraints

  • 0 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u, v < n, u != v

Example 1

n = 4
edges = [[0, 1], [0, 2], [1, 3], [2, 3]]

Step 1 builds {0}, step 2 builds {1, 2}, step 3 builds {3}. Output: [0, 3].

Example 2

n = 5
edges = [[0, 1], [2, 3], [3, 4]]

Step 1 builds {0, 2}, step 2 builds {1, 3}, step 3 builds {4}. Output: [4].

Be ready to extend your solution to targets with different build durations.

Clarifying questions

  • Are duplicate edges possible, and should they be ignored?
  • With n = 0, is the answer an empty list?
  • If a step builds exactly one target, but a target in another branch is idle, does it still count? (Only what builds in that step matters; confirm.)
  • What error should a cycle raise?

What a strong answer covers

  • Each target's step is 1 + max(step of its prerequisites), computed in one Kahn topological pass with in-degrees.
  • Counting targets per step, then returning, in step order, the targets of the steps that hold exactly one target.
  • Cycle detection from the same pass: if fewer than n targets were processed, there is a cycle.
  • O(n + e) time and space; both examples traced.
  • Tests: no edges (every target in step 1, so bottlenecks only when n = 1), a single chain (every target a bottleneck), a diamond, duplicate edges, a cycle.

Follow-ups

  • Targets have different durations: a target is a bottleneck if no other target is building at any moment while it builds.
  • Only p builders are available.
  • Find the critical path and which target to speed up to cut the total time most.
  • Edges are added over time: keep the answer current.

Where it's asked

What it tests

graphs · topological sort · bfs · scheduling

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding