Merge Intervals (LeetCode 56): Solution and Explanation
Given a list of intervals in any order, combine every group of overlapping intervals into a single interval and return the resulting list, which should contain no overlaps.
Watch it run step by step
Try your own input and write the code →Intuition
Without sorting, you could repeatedly scan for any two intervals that overlap, merge them, and start over until nothing changes. That works, but every merge can trigger another full scan, giving quadratic or worse behavior, and the bookkeeping is messy.
The problem becomes simple once intervals are sorted by start. In that order, an interval can only overlap with the group that is currently being built, the most recent merged interval, because everything before that group already ended earlier. So you never need to look further back than the last element of your output.
For each interval in sorted order there are only two cases. If its start is at or before the end of the last merged interval, it overlaps (or touches), so stretch that last interval's end to the larger of the two ends. The max matters because an interval can be fully contained in the previous one, like [2,3] inside [1,10]. If its start is after the last end, there is a gap, so it begins a new merged interval.
This sort-then-sweep pattern is worth recognizing because it shows up across many interval problems. Sorting by start time gives a natural processing order, and the answer can be built greedily with only the last result in view. Once you see intervals in an input, sorting by start is usually the first move to try.
Approach: Sort by start, then sweep
- Sort
intervalsby their start value. - Seed
outputwith the first interval, which is safe because the input always has at least one interval. - For each remaining
(start, end), readlastEndfrom the last interval inoutput. - If
start <= lastEnd, the intervals overlap, so set the last output interval's end tomax(lastEnd, end). - Otherwise append
[start, end]as a new interval. - Return
output.
Step-by-step example
intervals = [[1,3],[8,10],[2,6],[15,18]]
- Sorting by start gives [[1,3],[2,6],[8,10],[15,18]].
output = [[1,3]]. - [2,6]: 2 <= 3, so they overlap. The last interval becomes [1, max(3, 6)] = [1,6].
- [8,10]: 8 > 6, so there is a gap. Append it:
output = [[1,6],[8,10]]. - [15,18]: 15 > 10, so append it. Return [[1,6],[8,10],[15,18]]. Note that the original [1,3] list object was modified in place to become [1,6].
Code: Python, Java, C++
1class Solution:
2 def merge(self, intervals: List[List[int]]) -> List[List[int]]:
3 intervals.sort(key = lambda i: i[0])
4 output = [intervals[0]]
5
6 for start, end in intervals[1:]:
7 lastEnd = output[-1][1]
8
9 if start <= lastEnd:
10 output[-1][1] = max(lastEnd, end)
11 else:
12 output.append([start, end])
13 return output1class Solution {
2 public int[][] merge(int[][] intervals) {
3 Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
4 List<int[]> output = new ArrayList<>();
5 output.add(intervals[0]);
6
7 for (int i = 1; i < intervals.length; i++) {
8 int[] interval = intervals[i];
9 int[] last = output.get(output.size() - 1);
10
11 if (interval[0] <= last[1]) {
12 last[1] = Math.max(last[1], interval[1]);
13 } else {
14 output.add(interval);
15 }
16 }
17 return output.toArray(new int[output.size()][]);
18 }
19}1class Solution {
2public:
3 vector<vector<int>> merge(vector<vector<int>>& intervals) {
4 sort(intervals.begin(), intervals.end());
5 vector<vector<int>> output;
6 output.push_back(intervals[0]);
7
8 for (int i = 1; i < intervals.size(); i++) {
9 if (intervals[i][0] <= output.back()[1]) {
10 output.back()[1] = max(output.back()[1], intervals[i][1]);
11 } else {
12 output.push_back(intervals[i]);
13 }
14 }
15 return output;
16 }
17};Time and space complexity
O(n log n)
Sorting takes O(n log n). The sweep that follows looks at each interval once, which is O(n). For ten thousand intervals that is a trivial amount of work.
O(n)
The output can hold up to n intervals when none overlap, and the sort may use additional memory depending on the language.
Other approaches
Repeated pairwise merging (time O(n²), space O(n))
Keep scanning all pairs for an overlap, merge the first one found, and repeat until no overlaps remain. It needs no sort but is quadratic or worse and is mainly useful as a correctness check.
Counting sweep for bounded coordinates (time O(n + R), space O(R))
When endpoints are small integers, mark +1 at each start and -1 just after each end in a counting array, then walk the array and emit a merged interval each time the running count returns to zero. Be careful with touching intervals, which still need to merge.
Common mistakes
- Setting the merged end to the current interval's end instead of
max(lastEnd, end), which shrinks the interval when the current one is nested inside the previous one. - Using
start < lastEndinstead of<=, which fails to merge touching intervals like [1,4] and [4,5]. - Comparing each interval with its original neighbor instead of the last merged interval in
output, which misses chains of overlaps. - Forgetting to sort, which makes the single sweep incorrect for unordered input. Sorting by end time instead of start time also breaks the logic, because a long interval with a late end could then appear after shorter intervals it should absorb.
Frequently asked questions
Why do you need to sort intervals before merging?
Sorting by start guarantees that any interval overlapping the current one is the most recently merged interval. Without that order you would have to compare against everything seen so far.
What is the time complexity of merge intervals?
It is O(n log n) because of the sort, plus an O(n) sweep. The space is O(n) for the output list.
Should [1,4] and [4,5] be merged?
Yes. They share the point 4, so they merge into [1,5]. That is why the overlap test is start <= lastEnd.
Can I merge intervals in place?
Yes. After sorting, keep a write index and overwrite the array as you merge, then truncate. It avoids a separate output list, although the sort may still use extra memory.