Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in Swift: O(n log n) with Sorting and One Pass

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    SWIFT · INTERVALS

    Merge Intervals in Swift, explained

    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

    1. Sort by start. Declare sorted with let as intervals.sorted with the closure { $0[0] < $1[0] }. It returns a new array, because the parameter is a constant.
    2. Create merged with var as an empty [[Int]]. It holds the merged intervals in order of start.
    3. Loop over every interval in sorted. Write the closing brace right away.
    4. Name the two ends with one let: start is interval[0] and end is interval[1]. The next lines then read like the idea.
    5. Test whether a new merged interval begins. The condition is merged.isEmpty or the last merged end being less than start: merged[merged.count - 1][1] < start. Then append([start, end]). Use < and not <=, since touching intervals must merge.
    6. Otherwise extend the last interval. In the else, set the end of merged[merged.count - 1] to the larger of its end and end, with max.
    7. Return merged after 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:

    • sorted with a closure. $0 and $1 are the two intervals being compared, each an [Int]. The closure returns true when the first should come before the second. sorted leaves intervals unchanged 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 ||. When merged.isEmpty is true, Swift doesn't evaluate the right side. This matters, because merged[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 inside merged in place. This works because merged is a var.
    • Value semantics. Arrays are copied when assigned. The merged interval is a new [start, end] array, so changing it never affects the caller's intervals. 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 - 1 is the last index. merged.last returns 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 to end instead 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]].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free