Merge overlapping intervals
MetaSoftware Engineer · OnsiteLast updated
This problem tests your ability to manipulate array-based data by sorting and performing linear sweeps to consolidate overlapping ranges.
Problem Statement
Given an array of intervals where each interval is defined as [start, end], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.
Function Signature
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
Constraints
1 <= intervals.length <= 10^40 <= start_i <= end_i <= 10^4
Examples
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals that share a boundary point are considered overlapping.
Edge Cases
- Empty input list.
- A single interval.
- Intervals fully contained within another interval (e.g.,
[[1,10], [2,5]]). - Intervals already sorted or in reverse order.
Hints
Hint 1
Sorting the intervals based on their start times is a crucial first step to simplify the comparison process.
Hint 2
Once sorted, maintain a list of merged intervals and compare the current interval's start time with the end time of the last added merged interval.
Hint 3
If the current interval starts before or at the same time the previous interval ends, you must update the previous interval's end time to be the maximum of both.
Follow-up questions
- How would you modify your solution if the input intervals were not arrays, but a custom class `Interval { int start; int end; }`?
- What is the time and space complexity of your solution, and can you achieve O(1) auxiliary space if the input array is mutable and you are allowed to modify it?
- How would you approach the problem if you were asked to find the intersection of two lists of intervals instead of merging them?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.