DSA AnimatorDSA animations
Merge Intervals LC #56 Medium Intervals · Sort + Merge
Problem

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: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: [1,3] and [2,6] overlap → merge to [1,6]. [8,10] and [15,18] are disjoint.
Constraints: 1 ≤ intervals.length ≤ 10⁴  |  0 ≤ starti ≤ endi ≤ 10⁴
Try Examples
Custom intervals (e.g. 1,3 2,6 8,10):
Approach
Sort by Start + Linear Scan
Sort intervals by start. For each interval: if curr.start ≤ last.end → merge (extend end). Else → add as new.
Interval Timeline
Load an example to begin.
Variables
curr
—
last.end
—
Overlap?
—
Action
—
Step Logic
Press ▶ Play or Next Step to begin.
✓
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Sort intervals by start
2
If curr[0] > last[1] → no overlap, add curr as new
3
Else → overlap, merge: last[1] = max(last[1], curr[1])
Time
O(n log n)
Space
O(n)
Why It Works

After sorting by start, any interval that overlaps with the last merged interval must have curr.start ≤ last.end. Extending last.end captures the full overlap. Non-overlapping intervals start after last.end, so we add them fresh.

How to solve Merge Intervals

LeetCode 56 · Medium · Intervals · Pattern: Sort + Merge

Why the obvious approach is slow

Comparing every pair of intervals, and repeating until nothing changes, is O(n²) or worse. After sorting by start, overlapping intervals sit next to each other.

The key idea

Sort the intervals by start. Walk through them, and compare each one with the last merged interval. If it starts before that one ends, extend the end, otherwise start a new interval.

Remember

Sort by start, then merge with the last interval only. Overlap means the next start is at most the current end.

Run the animation above on your own input, or watch the 1:23 video explanation of Merge Intervals with a dry run and Java code.

More Intervals problems