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 see if any two can be glued together.
Here's how the algorithm would work step-by-step:
def merge(intervals):
merged_intervals_list = list(intervals)
# We loop continuously until a full pass completes without any overlapping merges
while True:
intervals_were_merged = False
for current_index in range(len(merged_intervals_list)):
for comparison_index in range(current_index + 1, len(merged_intervals_list)):
first_interval = merged_intervals_list[current_index]
second_interval = merged_intervals_list[comparison_index]
# Overlap check ensures we only combine intervals that actually touch or intersect
if (first_interval[0] <= second_interval[1]) and (second_interval[0] <= first_interval[1]):
new_start_value = min(first_interval[0], second_interval[0])
new_end_value = max(first_interval[1], second_interval[1])
combined_interval = [new_start_value, new_end_value]
merged_intervals_list.pop(comparison_index)
merged_intervals_list.pop(current_index)
merged_intervals_list.append(combined_interval)
intervals_were_merged = True
break
# Restarting the loop is necessary because list mutations invalidate current indexes
if intervals_were_merged:
break
# Terminate the while loop only when a complete iteration finds no overlapping pairs
if not intervals_were_merged:
break
return merged_intervals_listTo efficiently combine overlapping time blocks, we first organize all the blocks in chronological order based on when they start. Then, we walk through them from left to right, smoothly blending overlapping neighbors into a single continuous block.
Here's how the algorithm would work step-by-step:
def merge(intervals):
# Sorting by start time ensures overlapping blocks become adjacent neighbors.
sorted_intervals = sorted(intervals, key=lambda interval: interval[0])
merged_intervals = [sorted_intervals[0]]
for current_block in sorted_intervals[1:]:
most_recent_block = merged_intervals[-1]
# Overlapping blocks must be merged to maintain contiguous time ranges.
if current_block[0] <= most_recent_block[1]:
most_recent_block[1] = max(most_recent_block[1], current_block[1])
# Non-overlapping blocks start a new independent range in the result.
else:
merged_intervals.append(current_block)
return merged_intervals| Case | How to Handle |
|---|---|
| Empty input array | Check for null or empty array at the very beginning and return an empty array immediately. |
| Single interval in the input | Sorting and iteration skip the merge loop and safely return the single interval unchanged. |
| All intervals are already non-overlapping | Each interval is compared, fails the overlap condition, and is simply added to the output result list. |
| All intervals completely overlap into one large interval | The algorithm continuously updates the end time of a single running interval until all elements are merged. |
| Intervals with negative numbers and zero | Sorting handles negative numbers naturally because they evaluate smaller than zeros and positive values. |
| Intervals sharing exact boundary points like [1, 4] and [4, 6] | The merge condition uses less than or equal to the current end against the next start to successfully combine touching intervals. |
| Completely nested intervals such as [1, 5] and [2, 4] | Tracking the maximum end time across overlapping intervals prevents premature closing when a smaller interval is nested inside. |
| Extremely large inputs scaling near memory limits | An in-place or O(N log N) sorting approach ensures efficient time complexity while keeping auxiliary space minimal. |