Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in Scala: 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

    SCALA · INTERVALS

    Insert Interval in Scala, explained

    Problem overview

    The method insert receives intervals, an Array[Array[Int]] of intervals sorted by start with no two overlapping or touching, and newInterval, an Array[Int] holding a start and an end. It returns the intervals after inserting newInterval and merging it with every interval it overlaps. The result stays sorted, with no overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5].

    For [[1,3],[6,9]] and [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. With no intervals, [5,7] gives [[5,7]]. The lesson asks for O(n) time.

    Approach: before, overlapping, after

    Sorting everything again would cost O(n log n), and the input is already sorted, so one pass is enough. Because the intervals are sorted and don't overlap, the list splits into three consecutive parts:

    1. the intervals that end before the new one starts, which go into the answer unchanged;
    2. the intervals that overlap the new one, which all merge into a single interval;
    3. the intervals that start after the merged one ends, which go in unchanged.

    A single index i walks through the intervals once, and each part continues where the previous one stopped. In part two, the growing interval keeps its own start and end. Every interval that overlaps it can only widen it: an earlier start or a later end.

    Step by step

    1. Create result as an empty mutable.ArrayBuffer[Array[Int]], since the number of output intervals isn't known in advance.
    2. Store the length in val n and declare var i starting at 0.
    3. Part one, a while loop. It runs while i < n and intervals(i)(1) < newInterval(0), that is, while interval i ends before the new one starts. Use <: an interval that ends exactly where the new one starts touches it and must merge. Checking i < n first lets && stop before it reads past the end.
    4. Inside it, add intervals(i) to result with += and move on with i += 1.
    5. Part two begins with two vars, start and end, set to newInterval(0) and newInterval(1). They are var because merging changes them.
    6. A second while loop runs while i < n and intervals(i)(0) <= end. Every remaining interval ends at or after newInterval(0), so it overlaps the growing one exactly when it starts by end. Here <= is right, since an interval starting exactly at end touches it.
    7. Merge the start: start = math.min(start, intervals(i)(0)).
    8. Merge the end: end = math.max(end, intervals(i)(1)). The larger value matters when an interval lies completely inside the new one.
    9. Advance i += 1. Without it the loop would look at the same interval forever.
    10. Add the merged interval Array(start, end) to result. It goes after part one and before part three, which keeps the result sorted. If nothing overlapped, it is just newInterval.
    11. Part three, a third while loop runs while i < n. Every interval left starts after end, so none overlaps the merged one.
    12. Inside it, add intervals(i) and do i += 1, as in part one.
    13. End with result.toArray.

    The solution in Scala

    class Solution {
        def insert(intervals: Array[Array[Int]], newInterval: Array[Int]): Array[Array[Int]] = {
            val result = mutable.ArrayBuffer[Array[Int]]()
            val n = intervals.length
            var i = 0
            while (i < n && intervals(i)(1) < newInterval(0)) {
                result += intervals(i)
                i += 1
            }
            var start = newInterval(0)
            var end = newInterval(1)
            while (i < n && intervals(i)(0) <= end) {
                start = math.min(start, intervals(i)(0))
                end = math.max(end, intervals(i)(1))
                i += 1
            }
            result += Array(start, end)
            while (i < n) {
                result += intervals(i)
                i += 1
            }
            result.toArray
        }
    }
    

    The Scala details worth a closer look:

    • mutable.ArrayBuffer. It comes from scala.collection.mutable, which the lesson's code already has in scope. In a file of your own, add import scala.collection.mutable. An Array has a fixed size, while a buffer grows with +=.
    • val and var. result and n never get reassigned, so they are val. The index and the growing interval's ends change, so they are var. The buffer is a val whose contents still change.
    • while loops. The loop parts need an index that continues from one loop to the next, which is why this solution uses while and a shared var i rather than for loops with separate ranges.
    • && short-circuits. In i < n && intervals(i)(1) < ..., the right side is skipped when i < n is false, so intervals(i) is never read out of bounds.
    • Shared inner arrays. result += intervals(i) adds the same inner array as the input holds, not a copy. That is fine here because the method never modifies them.

    Complexity

    Time: O(n). The index i only moves forward and each interval is handled once across the three loops, with constant work each time.

    Space: O(n). The result holds up to n + 1 intervals. Beyond the output, only a few variables are used.

    Edge cases and common mistakes

    • No intervals. All three loops are skipped and the answer is just newInterval: [], [5,7] gives [[5,7]].
    • New interval before everything. [[3,5]] with [0,1] gives [[0,1],[3,5]]. Part one is empty and the new interval is added first.
    • New interval after everything. [[3,5]] with [7,9] gives [[3,5],[7,9]]. Part one takes the old interval and the new one follows.
    • Fits in a gap. [[1,2],[5,6]] with [3,4] gives [[1,2],[3,4],[5,6]].
    • Inside an existing interval. [[1,5]] with [2,3] gives [[1,5]], because the larger end keeps 5.
    • Touching on either side. [[1,4],[6,9]] with [4,6] gives [[1,9]], and [[3,5]] with [5,8] gives [[3,8]]. Using <= in the first loop or < in the second would leave touching intervals unmerged.
    • Swallowing everything. [[1,2],[3,4]] with [0,10] gives [[0,10]].
    • Forgetting i += 1. A while loop without it never ends.

    Testing

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