If you want to master array problems, “Merge Intervals” is a must-know question! In this blog, we’ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with comments, dry runs, and clear explanations.
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.
Here’s the [Problem Link] to begin with.
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 <= 104
Interactive Visualizer: Sort, Then Merge
Choose an example or type your own intervals, then press Next to follow the optimal solution. The orange bar is the interval being checked, and the green bars on the Merged row are the answer so far (blue when it was just extended).
Brute Force Solution
Intuition and Approach
Let’s solve the problem step by step in the simplest way:
- Sort the Intervals:
Sorting helps us line up all intervals so that overlapping intervals are next to each other. - Check Each Interval:
For every interval, try to merge it with all future intervals that overlap with it. - Skip Already Merged Intervals:
If an interval is already covered by a previous merge, skip it. - Why does this work?
We check every possible overlap and merge accordingly. This ensures all intervals are merged correctly, but it’s not the most efficient.
Code Implementation
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
n = len(intervals)
intervals.sort() # sort intervals by start time
ans = []
for i in range(n):
start, end = intervals[i][0], intervals[i][1] # current interval
# skip if current interval is already merged
if len(ans) != 0 and end <= ans[-1][1]:
continue
# try to merge with future overlapping intervals
for j in range(i + 1, n):
if intervals[j][0] <= end: # overlap found
end = max(end, intervals[j][1]) # extend end to the farthest overlap
else:
break # stop if no overlap
ans.append([start, end]) # add merged interval to answer
return ansPythonclass Solution {
public int[][] merge(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
: Integer.compare(a[1], b[1])); // sort by start time
List<int[]> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
int start = intervals[i][0], end = intervals[i][1]; // current interval
// skip if current interval is already merged
if (!ans.isEmpty() && end <= ans.get(ans.size() - 1)[1]) continue;
// try to merge with future overlapping intervals
for (int j = i + 1; j < n; j++) {
if (intervals[j][0] <= end) { // overlap found
end = Math.max(end, intervals[j][1]); // extend end to the farthest overlap
} else {
break; // stop if no overlap
}
}
ans.add(new int[]{start, end}); // add merged interval to answer
}
return ans.toArray(new int[ans.size()][]);
}
}class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int n = intervals.size();
sort(intervals.begin(), intervals.end()); // sort intervals by start time
vector<vector<int>> ans;
for (int i = 0; i < n; i++) {
int start = intervals[i][0], end = intervals[i][1]; // current interval
// skip if current interval is already merged
if (!ans.empty() && end <= ans.back()[1]) continue;
// try to merge with future overlapping intervals
for (int j = i + 1; j < n; j++) {
if (intervals[j][0] <= end) { // overlap found
end = max(end, intervals[j][1]); // extend end to the farthest overlap
} else {
break; // stop if no overlap
}
}
ans.push_back({start, end}); // add merged interval to answer
}
return ans;
}
};Code Explanation
- First, we sort the intervals to make overlapping intervals adjacent.
- For each interval, we check if it’s already merged; if so, we skip it.
- Then, we look ahead to merge all intervals that overlap with the current one.
- We add the merged interval to our answer list.
Dry Run
Input:intervals = [[1,3],[2,6],[8,10],[15,18]]
- After sorting:
[[1,3],[2,6],[8,10],[15,18]] - i = 0: start with
[1,3].[2,6]overlaps (2 ≤ 3), so merge to[1,6].[8,10]does not overlap (8 > 6), so stop and add[1,6]. - i = 1:
[2,6]ends at 6, which is not beyond the last merged end 6, so it was already merged. Skip it. - i = 2: start with
[8,10].[15,18]does not overlap, so add[8,10]. - i = 3: start with
[15,18]. There are no more intervals, so add[15,18]. - Final output:
[[1,6],[8,10],[15,18]]
Time and Space Complexity
- Time Complexity: O(N^2)
For each interval, we may check all future intervals. - Space Complexity: O(N)
For the answer list.
Conclusion
The brute force approach is easy to understand but slow for large lists. It’s good for learning the basics of the problem.
Optimal Solution
Intuition and Approach
We can solve this problem much faster by merging intervals as we go:
- Sort the Intervals:
Sorting puts overlapping intervals next to each other. - Merge on the Go:
As we go through each interval, check if it overlaps with the last interval in our answer list. If it does, merge them. If not, add it as a new interval. - Why does this work?
After sorting, all overlaps are adjacent, so we only need to look at the last merged interval.
Code Implementation
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
n = len(intervals)
intervals.sort() # sort intervals by start time
ans = []
for i in range(n):
# if ans is empty or no overlap, add interval
if len(ans) == 0 or intervals[i][0] > ans[-1][1]:
ans.append(intervals[i])
else:
# merge with the last interval in ans
ans[-1][1] = max(ans[-1][1], intervals[i][1])
return ansPythonclass Solution {
public int[][] merge(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
: Integer.compare(a[1], b[1])); // sort by start time
List<int[]> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
// if ans is empty or no overlap, add interval
if (ans.isEmpty() || intervals[i][0] > ans.get(ans.size() - 1)[1]) {
ans.add(intervals[i]);
} else {
// merge with the last interval in ans
int[] last = ans.get(ans.size() - 1);
last[1] = Math.max(last[1], intervals[i][1]);
}
}
return ans.toArray(new int[ans.size()][]);
}
}class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int n = intervals.size();
sort(intervals.begin(), intervals.end()); // sort intervals by start time
vector<vector<int>> ans;
for (int i = 0; i < n; i++) {
// if ans is empty or no overlap, add interval
if (ans.empty() || intervals[i][0] > ans.back()[1]) {
ans.push_back(intervals[i]);
} else {
// merge with the last interval in ans
ans.back()[1] = max(ans.back()[1], intervals[i][1]);
}
}
return ans;
}
};Code Explanation
- We sort the intervals.
- For each interval, if it doesn’t overlap with the last interval in the answer, we add it.
- If it does overlap, we merge it with the last interval by updating the end value.
Dry Run
Input:intervals = [[1,3],[2,6],[8,10],[15,18]]
- After sorting:
[[1,3],[2,6],[8,10],[15,18]] [1,3]: the answer is empty, so add it →[[1,3]][2,6]: overlaps with[1,3](2 ≤ 3), merge to[1,6]→[[1,6]][8,10]: no overlap (8 > 6), add →[[1,6],[8,10]][15,18]: no overlap (15 > 10), add →[[1,6],[8,10],[15,18]]
Time and Space Complexity
- Time Complexity: O(N log N)
Sorting dominates; merging is O(N). - Space Complexity: O(N)
For the answer list.
Conclusion
The optimal solution is efficient and elegant. It’s the best approach for interviews and large datasets.
Final Thoughts
The “Merge Intervals” problem is a great example of how sorting and merging can simplify complex problems. Start with brute force to understand the basics, then use the optimal solution for best performance.
Frequently Asked Questions
What is the Merge Intervals problem?
Given a list of intervals [start, end], merge every group of overlapping intervals and return the non-overlapping intervals that cover the same ranges. For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]].
Why do we sort the intervals first?
After sorting by start time, any interval that overlaps the merged ones must overlap the last merged interval. That means one comparison per interval is enough, instead of comparing every pair.
Do touching intervals like [1,4] and [4,5] merge?
Yes. In LeetCode 56 two intervals overlap when the next start is less than or equal to the current end, so [1,4] and [4,5] merge into [1,5].
What is the time and space complexity of Merge Intervals?
The optimal solution takes O(n log n) time because of the sort; the merge pass itself is O(n). It uses O(n) space for the output list, plus whatever space the sort needs.
Where is Merge Intervals used in real life?
The same idea is used to combine overlapping meeting slots in calendars, merge time ranges in logs, and join overlapping ranges in booking systems. Related problems include Insert Interval (LeetCode 57) and Non-overlapping Intervals (LeetCode 435).
For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.
