~/problems / Intervals

Shard rebalance with an overlap limit

medium 3 levels ~60 min OpenAI

Level 1 Trim overlaps

A shard owns an inclusive range of integer keys and is written as a string "id:start:end" (ids are distinct and contain no :; start <= end, both may be negative). The coverage of key k is how many shards contain k.

Implement trim_overlaps(limit, shards) -> list[str] so that no key is covered by more than limit shards:

  1. Sort the shards by start, then end, then id. This is the processing order.
  2. Take them one at a time. Measure coverage using only the shards already kept (with their possibly shifted ranges). Move the shard's start forward to the first key >= start whose coverage is below limit; if it already is, it stays put.
  3. If that makes start > end, drop the shard.

Earlier shards never move, so later shards give up their overlap. Return the kept shards, with their new ranges, in processing order.

trim_overlaps(1, ["A:0:100", "B:80:180"])
# ["A:0:100", "B:101:180"]

trim_overlaps(2, ["A:0:30", "B:0:31", "C:0:32", "D:0:100"])
# ["A:0:30", "B:0:31", "C:31:32", "D:32:100"]   C moves past A and B, then D past B and C

trim_overlaps(1, ["A:0:10", "B:3:8"])
# ["A:0:10"]   B would start at 11 > 8

Keys range over -10**9 .. 10**9 and there can be 2 * 10**4 shards, so you can't keep a count per key, and rescanning every kept shard for every new one is quadratic. Aim for O(n log n) overall.

Show hint

shards are processed in order of start, so to the right of the current shard's original start, coverage by the kept shards never increases as keys go up. That means only the kept shards' end values matter, and only the largest limit of them.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Intervals / sweep line. Sort by start, merge; sweep events for overlaps.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc