← Back to DSA Animator
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.