Example 1
- Input
- intervals = [[1,3],[2,6],[8,10],[15,18]]
- Output
- [[1,6],[8,10],[15,18]]
Intervals [1,3] and [2,6] overlap and merge into [1,6]; the other two touch nothing.
You are given an unsorted list of intervals and must combine every group of overlapping ones. Return the merged non-overlapping intervals covering exactly the same points.
Given an array intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals.
Two intervals overlap when they share at least one point, so touching intervals like [1,4] and [4,5] merge into [1,5]. Return the non-overlapping intervals covering exactly the same ranges as the input.
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4Intervals [1,3] and [2,6] overlap and merge into [1,6]; the other two touch nothing.
The intervals touch at 4, which counts as overlapping, so they merge into [1,5].
A zero-length closed interval still covers point 5. One interval needs no merge and is returned as an independently owned row.
The last interval [2,9] bridges the earlier disjoint blocks [1,3] and [8,10]. Absorbing just one block would leave overlapping output and fail to represent the fully merged result.
The nested interval contributes no new endpoints, and the point interval at 10 touches the outer interval. Taking the maximum end prevents the nested interval from shrinking the covered range.
Each merged block represents a connected covered range, so combining two overlapping intervals takes the smaller start and larger end. Touching endpoints count as overlap here. Example 1 combines [1,3] with [2,6] to form [1,6]. A new interval can bridge several existing blocks, so the unsorted approach must inspect every block; start-time sorting makes only the most recent merged block relevant.
Reveal Pairwise Merge: intuition, complexity, and code
[1,4] and [4,5] merge into [1,5].[2,3] inside [1,10] disappears into the outer bounds.Sorting by start lets finalized blocks stay closed: compare each incoming interval only with the final merged block, extending its maximum end or appending an owned new block.