medium Merge Intervals
Problem Statement
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into one [1,5].

Example 2:
Intervals: [[6,7], [2,4], [5,9]]
Output: [[2,4], [5,9]]
Explanation: Since the intervals [6,7] and [5,9] overlap, we merged them into one [5,9].
Example 3:
Intervals: [[1,4], [2,6], [3,5]]
Output: [[1,6]]
Explanation: Since all the given intervals overlap, we merged them into one.
Constraints:
- 1 <= intervals.length <= 104
intervals[i].length == 2- 0 <= starti <= endi <= 104
Try it yourself
Try solving this question here:
✅ Solution Merge Intervals
Problem Statement
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into one [1,5].

Example 2:
Intervals: [[6,7], [2,4], [5,9]]
Output: [[2,4], [5,9]]
Explanation: Since the intervals [6,7] and [5,9] overlap, we merged them into one [5,9].
Example 3:
Intervals: [[1,4], [2,6], [3,5]]
Output: [[1,6]]
Explanation: Since all the given intervals overlap, we merged them into one.
Constraints:
- 1 <= intervals.length <= 104
intervals[i].length == 2- 0 <= starti <= endi <= 104
Solution
Let’s take the example of two intervals (‘a’ and ‘b’) such that a.start <= b.start. There are four possible scenarios:

Our goal is to merge the intervals whenever they overlap. For the above-mentioned three overlapping scenarios (2, 3, and 4), this is how we will merge them:

To solve this problem, we will sort the list of intervals by their start times. This helps in easily identifying overlapping intervals. After sorting, we can iterate through the intervals, merging them if they overlap. We will maintain a list to store the merged intervals. As we iterate, we compare the current interval with the last interval in the merged list. If they overlap, we merge them by extending the end time. Otherwise, we add the current interval to the merged list.
This approach works because sorting brings overlapping intervals next to each other. This allows us to handle overlapping intervals in a single pass through the list. Sorting the intervals first is key to simplifying the merging process.
Step-by-Step Algorithm
-
Sort Intervals:
- Begin by sorting the list of intervals based on their start times.
- This can be done using a comparator in Java.
-
Initialize Merged List:
- Create an empty list called
mergedIntervalsto store the merged intervals.
- Create an empty list called
-
Set Initial Interval:
- Start by picking the first interval and set it as the current interval.
-
Iterate Through Intervals:
- Loop through the rest of the intervals.
- For each interval:
- Check Overlap:
- If the start of the current interval is less than or equal to the end of the previous interval, it means they overlap.
- In this case, merge them by updating the end of the previous interval to be the maximum of both ends.
- Non-overlapping:
- If they do not overlap, add the previous interval to the
mergedIntervalslist. - Update the current interval to be the next interval in the list.
- If they do not overlap, add the previous interval to the
- Check Overlap:
-
Add Last Interval:
- After the loop completes, add the last interval to the
mergedIntervalslist.
- After the loop completes, add the last interval to the
-
Return Result:
- Return the
mergedIntervalslist as the final output.
- Return the
Algorithm Walkthrough
Given input: [[1, 4], [2, 5], [7, 9]]
-
Sort Intervals:
- Original intervals:
[[1, 4], [2, 5], [7, 9]] - Sorted intervals:
[[1, 4], [2, 5], [7, 9]](already sorted)
- Original intervals:
-
Initialize Merged List:
- mergedIntervals:
[]
- mergedIntervals:
-
Set Initial Interval:
- Current interval:
[1, 4]
- Current interval:
-
Iterate Through Intervals:
- First Iteration:
- Next interval:
[2, 5] - Check overlap:
2 <= 4(True) - Merge intervals:
[1, 5] - Update current interval:
[1, 5]
- Next interval:
- Second Iteration:
- Next interval:
[7, 9] - Check overlap:
7 <= 5(False) - Add previous interval to mergedIntervals:
[[1, 5]] - Update current interval:
[7, 9]
- Next interval:
- First Iteration:
-
Add Last Interval:
- Add last interval to mergedIntervals:
[[1, 5], [7, 9]]
- Add last interval to mergedIntervals:
-
Return Result:
- mergedIntervals:
[[1, 5], [7, 9]]
- mergedIntervals:
Code
Here is what our algorithm will look like:
import java.util.*;
/*class Interval {
int start;
int end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
};*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() < 2) return intervals;
// sort the intervals by start time
Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start));
List<Interval> mergedIntervals = new LinkedList<Interval>();
Iterator<Interval> intervalItr = intervals.iterator();
Interval interval = intervalItr.next();
int start = interval.start;
int end = interval.end;
while (intervalItr.hasNext()) {
interval = intervalItr.next();
if (interval.start <= end) { // overlapping intervals, adjust the 'end'
end = Math.max(interval.end, end);
} else { // non-overlapping interval, add the previous interval and reset
mergedIntervals.add(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
// add the last interval
mergedIntervals.add(new Interval(start, end));
return mergedIntervals;
}
public static void main(String[] args) {
Solution sol = new Solution();
List<Interval> input = new ArrayList<Interval>();
input.add(new Interval(1, 4));
input.add(new Interval(2, 5));
input.add(new Interval(7, 9));
System.out.print("Merged intervals: ");
for (Interval interval : sol.merge(input)) System.out.print(
"[" + interval.start + "," + interval.end + "] "
);
System.out.println();
input = new ArrayList<Interval>();
input.add(new Interval(6, 7));
input.add(new Interval(2, 4));
input.add(new Interval(5, 9));
System.out.print("Merged intervals: ");
for (Interval interval : sol.merge(input)) System.out.print(
"[" + interval.start + "," + interval.end + "] "
);
System.out.println();
input = new ArrayList<Interval>();
input.add(new Interval(1, 4));
input.add(new Interval(2, 6));
input.add(new Interval(3, 5));
System.out.print("Merged intervals: ");
for (Interval interval : sol.merge(input)) System.out.print(
"[" + interval.start + "," + interval.end + "] "
);
System.out.println();
}
}
Time Complexity
The time complexity of the above algorithm is
Space Complexity
The space complexity of the above algorithm will be O(N) as we need to return a list containing all the merged intervals. We will also need O(N) space for sorting. For Java, depending on its version, Collections.sort() either uses Merge sort or Timsort, and both these algorithms need O(N) space. Overall, our algorithm has a space complexity of O(N).
Similar Problems
Problem 1: Given a set of intervals, find out if any two intervals overlap.
Example:
Intervals: [[1,4], [2,5], [7,9]]
Output: true
Explanation: Intervals [1,4] and [2,5] overlap
Solution: We can follow the same approach as discussed above to find if any two intervals overlap.
🤖 Don't fully get this? Learn it with Claude
Stuck on Merge Intervals? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Merge Intervals** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Merge Intervals** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Merge Intervals**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Merge Intervals**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.