Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in Swift: O(n) Single Pass in Three Parts

Practice O(n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. The list is sorted by start, and no two intervals overlap.

You also get one more interval, newInterval = [start, end].

Add newInterval to the list. Merge it with every interval it overlaps. Return an array of the resulting intervals, still sorted by start and with no overlaps.

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

 

Example 1:

Input: intervals = [[2,4],[7,9],[12,15]], newInterval = [8,13]
Output: [[2,4],[7,15]]
Explanation: [8,13] overlaps [7,9] and [12,15].
The three become [7,15].
[2,4] ends before 8. It stays as it is.

Example 2:

Input: intervals = [[1,2],[6,8]], newInterval = [3,5]
Output: [[1,2],[3,5],[6,8]]
Explanation: [3,5] fits in the gap between [1,2] and [6,8].
Nothing merges.

Example 3:

Input: intervals = [[0,3],[5,6]], newInterval = [3,5]
Output: [[0,6]]
Explanation: [3,5] touches [0,3] at 3.
It also touches [5,6] at 5.
All three join into one.

 

Constraints:

  • 0 to 100,000 intervals in intervals. The list can be empty.
  • Each start and end, in intervals and in newInterval, is from 0 to 1,000,000.
  • No start is greater than its end.
  • intervals is sorted by start.
  • Each interval ends before the next one starts (endi < starti+1). They don't even touch.

Note:

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

STEP 1 OF 13
    Ctrl + Enter to check

    SWIFT · INTERVALS

    Insert Interval in Swift, explained

    Problem overview

    The method insert receives intervals, an array of [Int] pairs (start and end) that is already sorted by start and has no two intervals overlapping, plus one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result, still sorted and without overlaps. Two intervals overlap when they share at least one point, so touching intervals like [1,4] and [4,5] merge into [1,5]. There can be up to 100,000 intervals, and the method must run in O(n) time.

    For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1, 5], [6, 9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] it is [[1, 2], [3, 10], [12, 16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so all four merge into [3, 10]. With no intervals and [5,7] the result is [[5, 7]].

    Approach: before, overlapping, after

    Because the input is already sorted and free of overlaps, there is no need to sort or to compare every pair. Walk through the intervals once, with an index i that carries over from one part to the next. Relative to newInterval they fall into three groups, in this order:

    1. Intervals that end before the new one starts. They can't overlap it and go into the result unchanged. The test is intervals[i][1] < newInterval[0]. An interval that ends exactly at the new start touches it, so it belongs to the next group.
    2. Intervals that overlap the new one. They all merge with it into one interval. Keep the growing interval in two variables, start and end, beginning with the new interval's values. An interval overlaps it as long as it starts at or before end: intervals[i][0] <= end. Each one can lower start or raise end.
    3. The remaining intervals. Each one starts after end, so none can overlap the merged interval. They go into the result unchanged.

    Between the second and third groups, the merged interval [start, end] is appended, so the result stays sorted by start.

    For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], group 1 is [1,2]. Group 2 starts with start = 4, end = 8. Reading [3,5] gives start = 3 and end = 8. Reading [6,7] changes nothing, because it lies inside. Reading [8,10] gives end = 10. The next interval, [12,16], starts after 10, so group 3 is [12,16]. A real run gives [[1, 2], [3, 10], [12, 16]].

    Each interval is looked at once, so the time is O(n).

    Step by step

    1. Create result with var as an empty [[Int]].
    2. Store intervals.count in n, and create the index i with var at 0. The index only moves forward, and each part continues where the previous one stopped.
    3. Part one: a while loop that runs while i < n and intervals[i][1] < newInterval[0]. Put i < n first: && stops evaluating there when the intervals run out, before intervals[i] is read.
    4. Copy and advance. Inside the loop, append intervals[i] to result and do i += 1.
    5. Start the merged interval. After the loop, declare start and end with one var, set from newInterval[0] and newInterval[1]. They are vars because they change as intervals merge in.
    6. Part two: a second while loop that runs while i < n and intervals[i][0] <= end. Use <=, because an interval that starts exactly at end touches the merged one and must merge.
    7. Lower the start inside it: start = min(start, intervals[i][0]). Only the first overlapping interval can start before the new one.
    8. Raise the end: end = max(end, intervals[i][1]). The larger value is needed because an interval can lie entirely inside the merged one.
    9. Advance with i += 1. Without it, the loop would look at the same interval forever.
    10. Append the merged interval [start, end] to result after the loop. If nothing overlapped, it is the new interval unchanged.
    11. Part three: a while loop that runs while i < n.
    12. Copy and advance as in part one.
    13. Return result.

    The solution in Swift

    class Solution {
        func insert(_ intervals: [[Int]], _ newInterval: [Int]) -> [[Int]] {
            var result: [[Int]] = []
            let n = intervals.count
            var i = 0
            while i < n && intervals[i][1] < newInterval[0] {
                result.append(intervals[i])
                i += 1
            }
            var start = newInterval[0], end = newInterval[1]
            while i < n && intervals[i][0] <= end {
                start = min(start, intervals[i][0])
                end = max(end, intervals[i][1])
                i += 1
            }
            result.append([start, end])
            while i < n {
                result.append(intervals[i])
                i += 1
            }
            return result
        }
    }
    

    The Swift details worth a closer look:

    • Short-circuit &&. In i < n && intervals[i][1] < newInterval[0], the right side runs only when i < n is true. Reading an array outside its bounds stops the program, so the order of the two conditions matters.
    • No parentheses around conditions. Swift's while and if don't need them, but braces are always required.
    • var start = ..., end = .... One var declares both variables. They are separate values: changing start doesn't affect end.
    • min and max. These are global functions that take two values of the same type.
    • Arrays of arrays are values. result.append(intervals[i]) adds a copy of that inner array, not a shared reference, and the caller's intervals is never changed.
    • Why while and not for. The index must carry over from one loop to the next, and each loop decides on its own when to stop. Three while loops sharing i express that directly.
    • Parameter labels. Both parameters are declared with _, so the call is insert(intervals, newInterval) with no labels.

    Complexity

    Time: O(n). The three loops share one index that only increases, so each interval is read once, and every step does constant work.

    Space: O(n) for the output. Besides the result, which can hold n + 1 intervals, the method uses only a few variables.

    Edge cases and common mistakes

    • No intervals. [] with [5,7] gives [[5, 7]]: all three loops are skipped and only the append runs.
    • New interval before everything. [[3,5]] with [0,1] gives [[0, 1], [3, 5]].
    • New interval after everything. [[3,5]] with [7,8] gives [[3, 5], [7, 8]].
    • Inside an existing interval. [[1,5]] with [2,3] gives [[1, 5]]. The max keeps the end at 5.
    • Touching on one side. [[1,3]] with [3,6] gives [[1, 6]], and [[1,2],[3,4]] with [2,3] gives [[1, 4]].
    • Covering everything. [[1,2],[6,7]] with [0,10] gives [[0, 10]].
    • Strict versus non-strict comparisons. Part one uses < and part two uses <=. Swapping either one would keep touching intervals apart.
    • Forgetting i += 1. A while loop without it never ends.
    • Appending the merged interval too early or too late. It must go after part one and before part three, or the result is out of order.

    Testing

    Results from running the reference solution:

    • [[1,3],[6,9]], [2,5] gives [[1, 5], [6, 9]].
    • [[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8] gives [[1, 2], [3, 10], [12, 16]].
    • [], [5,7] gives [[5, 7]].
    • [[3,5]], [0,1] gives [[0, 1], [3, 5]].
    • [[1,2],[3,4]], [2,3] gives [[1, 4]].
    • [[1,2],[6,7]], [0,10] gives [[0, 10]].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free