Fewest waves to roll an agent across a region tree

Agent buildHard40 min

Your task

A support agent is being switched on region by region, in waves. Every region except the seed regions has a source region: before it goes live, it replays its source's live traffic, so it can only go live in a wave after the one its source went live in. The on-call team can watch at most k regions in a wave.

Write fewest_waves(regions, k). regions lists every region once as [name, source], in any order. source is "" for a seed region and otherwise the name of another region in the list, and sources never form a cycle. Names are non-empty and can be any string, even "constructor", "toString" or "__proto__". k is at least 1, and there are at most 2,000 regions.

Return the smallest number of waves that gets every region live. A wave may hold fewer than k regions.

Examples:

  • fewest_waves([["us-east", ""], ["us-west", "us-east"], ["eu", "us-east"], ["eu-2", "eu"]], 2) returns 3: us-east, then us-west and eu, then eu-2.
  • fewest_waves([["a", ""], ["b", ""], ["c", ""], ["d", "c"]], 2) returns 2: c and a, then d and b.
  • fewest_waves([["hub", ""], ["x", "hub"], ["y", "hub"], ["z", "hub"]], 2) returns 3.

Examples

fewest_waves(regions: list[list[str]], k: int) -> int
Example 1
Inputfewest_waves([["us-east", ""], ["us-west", "us-east"], ["eu", "us-east"], ["eu-2", "eu"]], 2)
Output3
Example 2
Inputfewest_waves([["a", ""], ["b", ""], ["c", ""], ["d", "c"]], 2)
Output2
Example 3
Inputfewest_waves([["hub", ""], ["x", "hub"], ["y", "hub"], ["z", "hub"]], 2)
Output3