Problem Description
Given a list of intervals, where each interval represents a set of consecutive integers, find the minimum size of an array such that every interval contains at least two numbers from that array.
Key Insights
- Use a greedy strategy by processing intervals in order of increasing end points.
- Sort the intervals by end point (and in case of tie, by start in descending order) so that choosing numbers near the end maximizes coverage for future intervals.
- For each interval, count the numbers already chosen that fall into the interval.
- If fewer than two numbers are present, add the necessary number(s) (always choosing the largest possible values within the interval to maximize overlap with future intervals).
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting step where n is the number of intervals. Space Complexity: O(n) for storing the chosen numbers (in worst-case scenarios) plus auxiliary space for sorting.
Solution
The solution uses a greedy approach after sorting the intervals. First, the intervals are sorted by their end boundary, with a tie-breaker on the start boundary (in descending order) to ensure that when intervals share an end, the one with the larger start is handled last. For each interval, we check how many selected numbers (already added in our result set) fall inside the interval. If fewer than two, we add additional numbers at the end of the interval. This ensures that the numbers we add are as large as possible within the current interval, thereby maximizing the chance they will cover future intervals as well. The key idea is that by always “covering” an interval from the end, we are potentially covering as many subsequent intervals as possible.
Code Solutions
Below are the code solutions in Python, JavaScript, C++, and Java.