Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 104intervals[i].length == 20 <= starti <= endi <= 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a messy pile of time periods that overlap with each other, and you want to clean them up by combining the ones that touch or overlap. The brute force approach involves exhaustively comparing every single period against every other period to find overlaps, combining them, and repeating the process until nothing else can be combined.
Here's how the algorithm would work step-by-step:
def merge(intervals):
active_intervals = list(intervals)
# We loop indefinitely because merging can create new overlaps requiring another pass
while True:
merged_something = False
for current_index in range(len(active_intervals)):
if merged_something:
break
for other_index in range(current_index + 1, len(active_intervals)):
first_interval = active_intervals[current_index]
second_interval = active_intervals[other_index]
# Check if intervals overlap to determine if they need to be combined into one
if not (first_interval[1] < second_interval[0] or second_interval[1] < first_interval[0]):
combined_start = min(first_interval[0], second_interval[0])
combined_end = max(first_interval[1], second_interval[1])
new_interval = [combined_start, combined_end]
active_intervals.pop(other_index)
active_intervals.pop(current_index)
active_intervals.append(new_interval)
merged_something = True
break
# Terminate loop only when a full pass completes without triggering any merges
if not merged_something:
return active_intervalsTo efficiently combine overlapping periods, we first organize them by their starting times so we can process them in chronological order. As we go through them one by one, we either merge overlapping periods into a single larger period or keep them separate if they do not touch.
Here's how the algorithm would work step-by-step:
class Solution:
def merge(self, intervals: list[list[int]]) -> list[list[int]]:
if not intervals:
return []
# Sorting by start time ensures chronological order for proper overlap checking.
sorted_intervals = sorted(intervals, key=lambda current_interval: current_interval[0])
merged_intervals = [sorted_intervals[0]]
for current_interval in sorted_intervals[1:]:
latest_merged_interval = merged_intervals[-1]
# Overlapping intervals require merging to create a single continuous period.
if current_interval[0] <= latest_merged_interval[1]:
latest_merged_interval[1] = max(latest_merged_interval[1], current_interval[1])
else:
# Non-overlapping intervals mean we finalize the current and start a new one.
merged_intervals.append(current_interval)
return merged_intervals| Case | How to Handle |
|---|---|
| Empty input array | Return the empty array immediately without performing any operations. |
| Single interval array | Return the single interval directly as no merging is required. |
| Completely overlapping intervals | The merge logic absorbs smaller intervals inside the larger one and produces a single combined interval. |
| Disjoint intervals | The sorting step ensures they remain separate and are appended to the result without modification. |
| Intervals with negative numbers | Standard sorting and comparison naturally handle negative coordinate values. |
| Touch-only intervals where one ends at the exact start of another | Using a condition like current_start <= previous_end successfully merges touching boundaries. |
| Duplicate intervals | Sorting groups them together and the merge logic safely combines them into one. |
| Maximum possible integer values for start and end times | Ensure comparison logic avoids overflow in languages with fixed-width integers. |