Merge Intervals
Medium sorting · arrays
Description
Constraints
1 <= intervals <= 10000
Examples
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Hints (1)
- Sort by start; merge while the next start is within the current end.
Solutions
Sort by start then sweep. (requires "sort") · Time O(n log n) · Space O(n)
func mergeIntervals(intervals [][]int) [][]int {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
out := [][]int{}
for _, iv := range intervals {
if len(out) > 0 && iv[0] <= out[len(out)-1][1] {
if iv[1] > out[len(out)-1][1] {
out[len(out)-1][1] = iv[1]
}
} else {
out = append(out, []int{iv[0], iv[1]})
}
}
return out
}
Sort by start then sweep. · Time O(n log n) · Space O(n)
function mergeIntervals(intervals) {
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
const out = [];
for (const iv of sorted) {
if (out.length && iv[0] <= out[out.length - 1][1]) {
out[out.length - 1][1] = Math.max(out[out.length - 1][1], iv[1]);
} else out.push([...iv]);
}
return out;
}
Sort by start then sweep. · Time O(n log n) · Space O(n)
function mergeIntervals($intervals) {
sort($intervals);
$out = [];
foreach ($intervals as $iv) {
if ($out && $iv[0] <= $out[count($out) - 1][1]) {
$out[count($out) - 1][1] = max($out[count($out) - 1][1], $iv[1]);
} else {
$out[] = $iv;
}
}
return $out;
}
Sort by start then sweep. · Time O(n log n) · Space O(n)
def mergeIntervals(intervals):
out = []
for iv in sorted(intervals, key=lambda x: x[0]):
if out and iv[0] <= out[-1][1]:
out[-1][1] = max(out[-1][1], iv[1])
else:
out.append(list(iv))
return out
Sort by start then sweep. · Time O(n log n) · Space O(n)
function mergeIntervals(intervals: number[][]): number[][] {
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
const out: number[][] = [];
for (const iv of sorted) {
if (out.length && iv[0] <= out[out.length - 1][1]) {
out[out.length - 1][1] = Math.max(out[out.length - 1][1], iv[1]);
} else out.push([...iv]);
}
return out;
}
Create a free account to submit solutions, track progress and save problems.
Create account