Binary Search Optimization and Interval Consolidation
Heaps, Sorting & SearchModel answerLast updated
Find the minimal rate to process items within a time limit, then consolidate overlapping ranges into non-overlapping spans.
You're given two algorithmic challenges to solve:
Problem 1: Minimum Processing Rate
You have an array piles where piles[i] represents the size of the i-th pile, and an integer h representing total hours available. In each hour, you can process at most one pile at rate k items per hour. If a pile has fewer than k items, you finish it and wait until the next hour to start another pile.
Find the minimum integer rate k such that you can finish processing all piles within h hours.
Example:
- Input:
piles = [3, 6, 7, 11],h = 8 - Output:
4 - Explanation: At rate 4, it takes
ceil(3/4) + ceil(6/4) + ceil(7/4) + ceil(11/4) = 1 + 2 + 2 + 3 = 8hours.
Problem 2: Consolidate Overlapping Ranges
You have a collection of intervals where each interval is [start, end] with inclusive endpoints. Merge all overlapping or touching intervals and return a list of non-overlapping intervals sorted by start time.
Two intervals overlap if one's start is less than or equal to the other's end when considering their relative positions.
Example:
- Input:
[[1,3], [2,6], [8,10], [15,18]] - Output:
[[1,6], [8,10], [15,18]] - Explanation:
[1,3]and[2,6]overlap, so they merge into[1,6].
Constraints:
- All array values are positive integers
- For problem 1:
h >= len(piles)(enough time to process each pile) - For problem 2: interval endpoints are valid (start ≤ end)
Hints
Hint 1
For the rate problem, if a rate k works, does any rate larger than k also work? What does this tell you about the search space?
Hint 2
When checking if a rate is sufficient, how do you handle partial piles without using floating-point division?
Hint 3
For interval consolidation, what happens when you process intervals in sorted order? When should you extend vs. start fresh?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem 1: Minimum Processing Rate
Approach
This is a classic binary search on the answer space problem. The key insight is recognizing monotonicity: if rate k allows finishing within h hours, then any rate k' > k also works. This means we can binary search for the smallest feasible k.
The search range is [1, max(piles)] because:
- We need at least rate 1 to make progress
- We never need more than
max(piles)since that processes the largest pile in one hour
For each candidate rate k, we check feasibility by calculating total hours needed:
total_hours = sum of ceil(pile / k) for each pile
Implementation Details
Integer ceiling division: To avoid floating-point errors, use (pile + k - 1) // k instead of math.ceil(pile / k).
Binary search pattern: Use the "find leftmost valid" template where we shrink the right boundary when feasible.
Code
def min_processing_rate(piles, h):
def hours_needed(rate):
"""Calculate hours required at given rate"""
return sum((pile + rate - 1) // rate for pile in piles)
left, right = 1, max(piles)
result = right
while left <= right:
mid = (left + right) // 2
if hours_needed(mid) <= h:
result = mid # This rate works, try smaller
right = mid - 1
else:
left = mid + 1 # Too slow, need faster rate
return result
Complexity
- Time: O(n log m) where n = len(piles), m = max(piles). Binary search runs log m iterations, each checking all n piles.
- Space: O(1)
Edge Cases
- Single pile: returns
ceil(pile / h) - h equals number of piles: must use max(piles) rate
- Very large piles with small h: requires high rates
Problem 2: Consolidate Overlapping Ranges
Approach
The strategy is to sort intervals by start time, then make a single pass to merge overlapping ranges.
Maintain a "current merged interval" and for each new interval:
- If it overlaps with current (new start ≤ current end), extend current's end to the maximum
- Otherwise, save current to results and start a new merged interval
The key insight: after sorting, we only need to compare each interval with the current merged one, not all previous intervals.
Implementation Details
Overlap condition: intervals[i][0] <= current_end determines if interval i overlaps with or touches the current merged span.
Edge cases: Handle empty input and single-interval inputs directly.
Code
def merge_intervals(intervals):
if not intervals:
return []
# Sort by start time
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
start, end = intervals[i]
if start <= current_end:
# Overlapping or touching - extend current interval
current_end = max(current_end, end)
else:
# Gap detected - save current and start new
merged.append([current_start, current_end])
current_start, current_end = start, end
# Don't forget the last interval
merged.append([current_start, current_end])
return merged
Complexity
- Time: O(n log n) for sorting, O(n) for merging pass = O(n log n) overall
- Space: O(n) for output (O(log n) or O(n) for sorting depending on implementation)
Edge Cases
- No intervals: return empty list
- No overlaps: return sorted copy of input
- All intervals overlap: return single merged interval
- Nested intervals like
[[1,5], [2,3]]: correctly produces[[1,5]]
Common Mistakes
Problem 1:
- Using floating-point division leading to precision errors
- Wrong binary search bounds or termination
- Forgetting that partial piles still consume a full hour
Problem 2:
- Forgetting to sort first
- Incorrect overlap condition (using
<instead of<=) - Not updating the end to the maximum when merging
- Forgetting to append the final merged interval