Problem overview
The method merge receives intervals, an array in which each interval is an [Int] holding a start and an end. It merges every group of overlapping intervals and returns the intervals that remain, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5]. There are 1 to 100,000 intervals, and the method must run in O(n log n) time.
For [[1,3],[2,6],[8,10],[15,18]] the result is [[1, 6], [8, 10], [15, 18]]: the first two overlap and merge, and the others stand alone. For [[1,4],[4,5]] the result is [[1, 5]]. For the unsorted [[6,8],[1,9],[2,4],[4,7]] it is [[1, 9]], because [1,9] covers all the others.
Approach: sort by start, then extend the last interval
Comparing every pair of intervals would take O(n²) time. Sorting by start brings the intervals that overlap next to each other, so one pass is enough.
Keep a list merged of the finished intervals, in order. Its last interval is the only one that can still grow. For each interval in sorted order, there are two cases:
- It starts after the last merged interval ends. It can't overlap anything merged so far, so it begins a new merged interval.
- Otherwise it overlaps the last merged interval. Extend that interval's end to the larger of its own end and this interval's end. The larger is needed because an interval can lie completely inside the last one:
[2,3]inside[1,10]must leave the end at 10.
Only the end ever changes. Because of the sorting, the new interval's start is never before the merged interval's start.
This is the pass over [[1,3],[2,6],[8,10],[15,18]], printed by a real run. Each line shows the interval just read and merged after it:
[1, 3] [[1, 3]]
[2, 6] [[1, 6]]
[8, 10] [[1, 6], [8, 10]]
[15, 18] [[1, 6], [8, 10], [15, 18]]
The sort costs O(n log n) and the pass costs O(n), so the sort dominates.
Step by step
- Sort by start. Declare
sortedwithletasintervals.sortedwith the closure{ $0[0] < $1[0] }. It returns a new array, because the parameter is a constant. - Create
mergedwithvaras an empty[[Int]]. It holds the merged intervals in order of start. - Loop over every
intervalinsorted. Write the closing brace right away. - Name the two ends with one
let:startisinterval[0]andendisinterval[1]. The next lines then read like the idea. - Test whether a new merged interval begins. The condition is
merged.isEmptyor the last merged end being less thanstart:merged[merged.count - 1][1] < start. Thenappend([start, end]). Use<and not<=, since touching intervals must merge. - Otherwise extend the last interval. In the
else, set the end ofmerged[merged.count - 1]to the larger of its end andend, withmax. - Return
mergedafter the loop. Every interval went into some merged one, in order of start.
The solution in Swift
class Solution {
func merge(_ intervals: [[Int]]) -> [[Int]] {
let sorted = intervals.sorted { $0[0] < $1[0] }
var merged: [[Int]] = []
for interval in sorted {
let start = interval[0], end = interval[1]
if merged.isEmpty || merged[merged.count - 1][1] < start {
merged.append([start, end])
} else {
merged[merged.count - 1][1] = max(merged[merged.count - 1][1], end)
}
}
return merged
}
}
The Swift details worth a closer look:
sortedwith a closure.$0and$1are the two intervals being compared, each an[Int]. The closure returnstruewhen the first should come before the second.sortedleavesintervalsunchanged and returns a new array.- Several constants in one
let.let start = interval[0], end = interval[1]declares two constants in one statement. - Short-circuit
||. Whenmerged.isEmptyis true, Swift doesn't evaluate the right side. This matters, becausemerged[merged.count - 1]on an empty array would stop the program with an index error. - Nested subscripts can be assigned.
merged[merged.count - 1][1] = ...changes the last interval insidemergedin place. This works becausemergedis avar. - Value semantics. Arrays are copied when assigned. The merged interval is a new
[start, end]array, so changing it never affects the caller'sintervals. Copying is cheap, because Swift copies an array's storage only when one of the copies is changed. - Index of the last element.
merged.count - 1is the last index.merged.lastreturns an optional and can't be assigned through like this, which is why the code uses the index.
Complexity
Time: O(n log n). Sorting takes O(n log n). The loop does constant work per interval.
Space: O(n). sorted is a sorted copy of the input, and merged can hold up to n intervals when nothing overlaps.
Edge cases and common mistakes
- One interval.
[[5,5]]returns[[5, 5]]. - Touching intervals.
[[1,4],[4,5]]returns[[1, 5]]. Using<=in the test would keep them apart. - Disjoint intervals.
[[1,2],[3,4]]stays as[[1, 2], [3, 4]]. - Nested intervals.
[[1,10],[2,3]]returns[[1, 10]]. Setting the end toendinstead of the larger value would shrink it to 3. - Unsorted input.
[[2,3],[1,10]]returns[[1, 10]]. Without sorting, the pass would find the intervals in the wrong order and miss overlaps. - Same start.
[[1,4],[0,4]]returns[[0, 4]]after sorting. - Merging by start only. Sorting is needed, but sorting alone isn't enough: comparing the new start with the last merged end is the key test.
Testing
Results from running the reference solution:
[[1,3],[2,6],[8,10],[15,18]]gives[[1, 6], [8, 10], [15, 18]].[[1,4],[4,5]]gives[[1, 5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1, 9]].[[1,10],[2,3]]gives[[1, 10]].[[1,2],[3,4]]gives[[1, 2], [3, 4]].[[5,5]]gives[[5, 5]].
