Trim Overlapping Ranges to Limit Capacity
Greedy & IntervalsModel answerLast 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,0000 <= start <= end <= 1,000,0001 <= k <= n- The returned list should contain valid intervals
[start, end]wherestart <= 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`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The task requires us to ensure that at no integer timestamp do more than k intervals overlap. Since the concurrency level can only increase at timestamps where an interval begins, we can process the intervals sorted by their start coordinate using a sweep-line algorithm combined with a min-heap.
- Sort & Group: First, sort all intervals by their
startvalue. Group them by unique start points so we can process all intervals starting at the same coordinatextogether. - Min-Heap for Active Intervals: Maintain a min-heap storing active intervals, prioritized by their
endcoordinate. We also keep track of each interval's original index to preserve output ordering if needed. - Sweep through Start Coordinates: At each distinct start coordinate
x:- Purge Expired: Remove all intervals from the heap whose
endis less thanx, as they no longer overlap with pointx. - Add New: Insert all intervals starting at
xinto the heap. - Enforce Limit
k: While the size of the heap exceedsk, pop the interval with the smallest end coordinate.- If its
start < x, truncate its end coordinate tox - 1and store it in our final output list. (It will no longer be active atx). - If its
start == x, truncating it tox - 1makesstart > end, so the interval is discarded completely.
- If its
- Purge Expired: Remove all intervals from the heap whose
- Final Collect: After processing all distinct start points, any intervals remaining in the heap are valid and keep their original
endcoordinates.
This greedy choice (truncating the interval that ends earliest among active overlapping intervals) immediately reduces the concurrency at point x while leaving intervals that extend further into the future intact.
Python 3 Code
import heapq
from collections import defaultdict
def rebalance_shards(intervals: list[tuple[int, int]], k: int) -> list[tuple[int, int]]:
if not intervals:
return []
# Group intervals by their start point
starts_map = defaultdict(list)
for i, (s, e) in enumerate(intervals):
starts_map[s].append((e, s, i))
unique_starts = sorted(starts_map.keys())
# Min-heap storing tuples: (end_time, start_time, original_index)
active_heap = []
result = []
for x in unique_starts:
# Remove intervals that ended before x
while active_heap and active_heap[0][0] < x:
end, start, idx = heapq.heappop(active_heap)
result.append((idx, start, end))
# Add all intervals starting at x
for item in starts_map[x]:
heapq.heappush(active_heap, item)
# Overlap limit enforcement
while len(active_heap) > k:
end, start, idx = heapq.heappop(active_heap)
# Truncate to end at x - 1
new_end = x - 1
if start <= new_end:
result.append((idx, start, new_end))
# If start > new_end, the interval is dropped entirely
# Add remaining active intervals that survived past all start points
while active_heap:
end, start, idx = heapq.heappop(active_heap)
result.append((idx, start, end))
# Sort output to match original relative ordering
result.sort(key=lambda item: item[0])
return [(start, end) for idx, start, end in result]
Complexity Analysis
-
Time Complexity:
- Grouping and sorting unique start coordinates takes $O(N \log N)$.
- Each interval is pushed to the heap once and popped at most once. Heap operations take $O(\log N)$ time.
- Re-sorting the final result by original index takes $O(N \log N)$.
- Overall Time Complexity: $O(N \log N)$, which easily satisfies the $O(N^2)$ restriction.
-
Space Complexity:
- The heap and result lists store at most $N$ elements.
- Overall Auxiliary Space Complexity: $O(N)$.