Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in Go: One Pass in Three Parts, O(n)

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

    GO · INTERVALS

    Insert Interval in Go, explained

    Problem overview

    The method insert receives intervals, a slice of []int pairs (start, end) that is already sorted by start with no two intervals overlapping or touching, and one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result, still sorted and with no overlaps. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they merge into [1,5].

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

    Approach: before, overlapping, after

    The input is already sorted and free of overlaps, so there is no need to sort again or compare every pair. A single left-to-right pass handles it in O(n), because the intervals fall into three groups, in this order:

    1. Before. Intervals that end before the new one starts. They go into the answer unchanged.
    2. Overlapping. Intervals that start no later than the end of the growing new interval. They all merge with it. Each can only widen it, with an earlier start or a later end.
    3. After. The rest. They start after the merged interval ends, so none can overlap it, and they go into the answer unchanged.

    One index i walks through the intervals once, and each loop picks up where the one before it stopped.

    For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], [1,2] ends at 2, before 4, so it is in the first group. Then [3,5], [6,7] and [8,10] each start at 8 or earlier, the current end, so they merge: the start drops to 3 and the end grows to 10. [12,16] starts after 10 and lands in the third group.

    Step by step

    1. Create result as an empty [][]int.
    2. Store len(intervals) in n and start the index i at 0.
    3. Part one: a loop with only a condition, which is Go's while. It runs while i < n and intervals[i][1] < newInterval[0]. The test is <, because an interval ending exactly where the new one starts touches it, and touching intervals merge.
    4. Inside it, append intervals[i] to result, keep what append returns, and do i++.
    5. Part two: keep the growing interval in start, end := newInterval[0], newInterval[1].
    6. Loop while i < n and intervals[i][0] <= end. Every interval left ends at or after newInterval[0], so it overlaps exactly when it starts by end. Here <= is right, because one that starts exactly at end touches it.
    7. Set start to min(start, intervals[i][0]).
    8. Set end to max(end, intervals[i][1]). The larger end matters when an interval lies fully inside the new one.
    9. Move i on with i++. Without it, the loop would look at the same interval forever.
    10. Append the merged interval []int{start, end} to result. If nothing overlapped, start and end are still the new interval's own, so it goes in unchanged.
    11. Part three: loop while i < n, as everything left starts after end.
    12. Append each remaining interval and do i++.
    13. Return result.

    The solution in Go

    type Solution struct {}
    
    func (this Solution) insert(intervals [][]int, newInterval []int) [][]int {
        result := [][]int{}
        n := len(intervals)
        i := 0
        for i < n && intervals[i][1] < newInterval[0] {
            result = append(result, intervals[i])
            i++
        }
        start, end := newInterval[0], newInterval[1]
        for i < n && intervals[i][0] <= end {
            start = min(start, intervals[i][0])
            end = max(end, intervals[i][1])
            i++
        }
        result = append(result, []int{start, end})
        for i < n {
            result = append(result, intervals[i])
            i++
        }
        return result
    }
    

    The Go details worth a closer look:

    • Go has no while. A for with only a condition does the same job: for i < n { ... } repeats as long as the condition holds.
    • Order inside && matters. && stops at the first false operand, so i < n goes first and intervals[i] is never read when the intervals have run out. With the two tests swapped, the read could go past the end and panic with index out of range.
    • append may reallocate. Always store its result back in result.
    • Appended intervals are shared, not copied. result = append(result, intervals[i]) adds the same inner slice that the caller holds. Changing result[0][0] afterwards also changes the caller's interval. The merged interval, built with []int{start, end}, is new.
    • Built-in min and max. They exist since Go 1.21, with no import. The lessons use Go 1.22.
    • Multiple assignment with :=. start, end := newInterval[0], newInterval[1] declares both in one statement.

    Complexity

    Time: O(n). The index i only moves forward and never steps back, so across the three loops each interval is handled once.

    Space: O(n) for result, which holds up to n + 1 intervals.

    Edge cases and common mistakes

    • Touching intervals. [[1,4]] with [4,5] gives [[1,5]]. If part one used <=, the interval [1,4] would be moved to the answer untouched and [4,5] would not merge with it.
    • Empty input. With no intervals, no loop runs except the append, and the answer holds only the new interval.
    • A new interval before everything. [[3,5]] with [1,2] gives [[1,2],[3,5]]. Part one is empty and the whole input lands in part three.
    • A new interval after everything. [[1,5]] with [6,8] gives [[1,5],[6,8]].
    • A new interval in a gap. [[1,2],[5,6]] with [3,4] gives [[1,2],[3,4],[5,6]].
    • A new interval inside an old one. [[1,5]] with [2,3] gives [[1,5]], because max keeps the end at 5.
    • A new interval that covers everything. [[1,2],[3,4]] with [0,10] gives [[0,10]].
    • Forgetting i++. The overlap loop never ends.

    Testing

    • [[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]].
    • [[1,4]], [4,5] gives [[1,5]].
    • [[1,2],[5,6]], [3,4] gives [[1,2],[3,4],[5,6]].
    • [[1,2],[3,4]], [2,3] gives [[1,4]].
    • [[1,2],[3,4]], [0,10] gives [[0,10]].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free