KatInterview

Binary Search Optimization and Interval Consolidation

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbinary-searchintervalsgreedy

Last 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 = 8 hours.

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?