Problem
Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them.
Examples
Example 1
Input: intervals = [[0, 3], [2, 6], [3, 4], [6, 9]]
Output: [3, 6]
Explanation:
- The set [3, 6] covers all intervals.
- Interval [0, 3] is covered by 3.
- Interval [2, 6] is covered by 3 and 6.
- Interval [3, 4] is covered by 3.
- Interval [6, 9] is covered by 6.
Solution
Method 1 - Sorting
To cover all intervals with the minimum number of points, we can focus on the end points of the intervals. By sorting intervals by their endpoints, we can efficiently determine the smallest set of points required to cover the intervals. Whenever a point from the sorted intervals is not covered, it can be added to the solution set.
Approach
- Sort the intervals by their end points.
- Initialize a list to store the points that will cover the intervals.
- Iterate through each sorted interval:
- If the current interval’s start is not covered by the last added point, add the current interval’s endpoint to the list.
- Return the list of points covering all intervals.
Code
Java
public class Solution {
public List<Integer> findMinimumPoints(int[][] intervals) {
if (intervals.length == 0) {
return new ArrayList<>();
}
// Sort intervals by their end points
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
List<Integer> result = new ArrayList<>();
int point = intervals[0][1];
result.add(point);
for (int[] interval : intervals) {
if (interval[0] > point) {
point = interval[1];
result.add(point);
}
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] intervals = {{0, 3}, {2, 6}, {3, 4}, {6, 9}};
System.out.println(solution.findMinimumPoints(intervals)); // Output: [3, 6]
}
}
Python
class Solution:
def findMinimumPoints(self, intervals: List[List[int]]) -> List[int]:
if not intervals:
return []
# Sort intervals by their end points
intervals.sort(key=lambda x: x[1])
result = []
point = intervals[0][1]
result.append(point)
for interval in intervals:
if interval[0] > point:
point = interval[1]
result.append(point)
return result
# For testing the solution
if __name__ == "__main__":
solution = Solution()
intervals = [[0, 3], [2, 6], [3, 4], [6, 9]]
print(solution.findMinimumPoints(intervals)) # Output: [3, 6]
Complexity
- ⏰ Time complexity:
O(n log n)
- Sorting:
O(n log n)
, withn
being the number of intervals. - Iteration:
O(n)
for iterating through the sorted intervals.
- Sorting:
- 🧺 Space complexity:
O(1)
for the list tracking points.