KatInterview

Trim Overlapping Ranges to Limit Capacity

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalsintervalssweep-lineheap

Last updated

Truncate overlapping integer intervals so no point is covered by more than k ranges while minimizing the total removed coverage.

In a distributed log collector, incoming worker tasks reserve time windows represented as inclusive integer intervals [start, end]. To prevent system bottlenecks, no single integer timestamp may be covered by more than k active tasks simultaneously.

You are given a list of n inclusive intervals intervals and a maximum concurrency limit k. If at any timestamp the number of overlapping intervals exceeds k, you must resolve the contention by trimming intervals.

To minimize disruption to active work, apply a greedy strategy: whenever the number of active intervals at a timestamp exceeds k, shorten the active interval that ends earliest so that it stops right before the current timestamp (i.e., its new end becomes timestamp - 1). If this causes the interval's start to exceed its end, remove the interval entirely.

Write a function rebalance_shards(intervals: list[tuple[int, int]], k: int) -> list[tuple[int, int]] that returns the updated list of intervals after enforcing the capacity constraint using this strategy.

Example 1

Input: intervals = [(1, 5), (2, 6), (3, 7)], k = 2
Output: [(1, 2), (2, 6), (3, 7)]

Explanation: At point 3, three intervals overlap: (1, 5), (2, 6), and (3, 7). The overlap count exceeds k = 2. The active interval with the earliest ending point is (1, 5). It is trimmed to end at 3 - 1 = 2, giving (1, 2). After this adjustment, no point has more than 2 overlaps.

Example 2

Input: intervals = [(1, 4), (1, 4), (1, 4)], k = 1
Output: [(1, 4)]

Explanation: At point 1, three intervals start simultaneously. Since k = 1, two intervals ending at 4 are trimmed to end at 0 (which makes them invalid start > end), leaving only one interval remaining.

Constraints

  • 1 <= n <= 100,000
  • 0 <= start <= end <= 1,000,000
  • 1 <= k <= n
  • The returned list should contain valid intervals [start, end] where start <= end, ordered by their original starting positions.

Hints

Hint 1

Overlaps can only increase at points where a new interval begins. You only need to inspect timestamps corresponding to interval start points.

Hint 2

Maintain a min-heap of active intervals ordered by their end times.

Hint 3

When the number of active intervals at the current start coordinate exceeds k, repeatedly extract the interval with the smallest end time and truncate its right endpoint to `current_start - 1`.