Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in Kotlin: One O(n) 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

    KOTLIN · INTERVALS

    Insert Interval in Kotlin, explained

    Problem overview

    The function insert receives intervals, an Array<IntArray> of [start, end] pairs that is already sorted by start and has no overlaps, and one more pair, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result as an Array<IntArray>, still sorted and without overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5]. The statement asks for O(n) time, where n is the number of intervals, which can reach 100,000.

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

    Approach: before, overlapping, after

    Because the input is already sorted, there is no need to sort it again, which would cost O(n log n). Walking through the list once, every existing interval falls into one of three groups, in this order:

    1. Before. The interval ends before the new interval starts. It can't touch the new one and goes into the answer unchanged.
    2. Overlapping. The interval starts no later than the end of the new interval, and it isn't in the first group, so it ends at or after the new interval's start. All of these merge with the new interval into one. Each can only widen it, with an earlier start or a later end.
    3. After. The interval starts after the end of the merged interval, and so does every later one, because the list is sorted. They go into the answer unchanged.

    The merged interval is added between the first and the third group, so the result stays sorted. If nothing overlaps, the merged interval is just newInterval, and it lands in its correct place.

    Here is how the second example moves through the three parts:

    part 1 keeps [1, 2]
    part 2 merges [3, 5] -> [3, 8]
    part 2 merges [6, 7] -> [3, 8]
    part 2 merges [8, 10] -> [3, 10]
    part 3 keeps [12, 16]
    

    Step by step

    1. Create result as an empty mutableListOf<IntArray>(). Its size isn't known up front.
    2. Store intervals.size in n and create an index var i = 0. All three loops share i, and each continues where the last one stopped.
    3. Part one loop: while (i < n && intervals[i][1] < newInterval[0]). Use <, because an interval that ends exactly where the new one starts touches it and must merge. Check i < n first, so that the right side isn't read once the intervals run out.
    4. Inside it, add intervals[i] to result and do i++.
    5. Create start and end as vars set to newInterval[0] and newInterval[1]. They describe the growing merged interval.
    6. Part two loop: while (i < n && intervals[i][0] <= end). Here <= is right, since an interval that starts exactly at end touches the merged one.
    7. Merge the start: start = minOf(start, intervals[i][0]).
    8. Merge the end: end = maxOf(end, intervals[i][1]). The larger value is needed because an interval can lie completely inside the new one.
    9. Advance with i++. Without it the loop would repeat forever on the same interval.
    10. Add the merged interval with result.add(intArrayOf(start, end)), after the loop.
    11. Part three loop: while (i < n), since everything left starts after the merged interval.
    12. Inside it, add intervals[i] and do i++.
    13. Return result.toTypedArray(), which converts the list to an Array<IntArray>.

    The solution in Kotlin

    class Solution {
        fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
            val result = mutableListOf<IntArray>()
            val n = intervals.size
            var i = 0
            while (i < n && intervals[i][1] < newInterval[0]) {
                result.add(intervals[i])
                i++
            }
            var start = newInterval[0]
            var end = newInterval[1]
            while (i < n && intervals[i][0] <= end) {
                start = minOf(start, intervals[i][0])
                end = maxOf(end, intervals[i][1])
                i++
            }
            result.add(intArrayOf(start, end))
            while (i < n) {
                result.add(intervals[i])
                i++
            }
            return result.toTypedArray()
        }
    }
    

    The Kotlin details worth a look:

    • Short-circuit &&. When i < n is false, the right side isn't evaluated, so intervals[i] never goes out of bounds. Swapping the two conditions would throw an ArrayIndexOutOfBoundsException when the intervals run out.
    • while and a shared var. Kotlin has no way to resume a for loop from a given index, so a var i and three while loops fit this pattern well. A val index couldn't be incremented.
    • Shared arrays. result.add(intervals[i]) adds the same IntArray object that the input holds, not a copy. The unchanged intervals in the result are the input's own arrays. The merged interval is a fresh array made by intArrayOf.
    • minOf and maxOf are standard-library functions and need no import.
    • mutableListOf versus toTypedArray(). A MutableList grows with add, and toTypedArray() produces the Array<IntArray> the signature requires.

    Complexity

    Time: O(n). The index i only moves forward, and every interval is looked at by exactly one of the three loops, with constant work each.

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

    Edge cases and common mistakes

    • Empty input. [] with [5,7] skips parts one and two, adds [5,7] and returns [[5,7]].
    • New interval first. [[3,5]] with [0,1] returns [[0,1],[3,5]]. Part one is empty, and the merged interval comes before the rest.
    • New interval last. [[3,5]] with [8,9] returns [[3,5],[8,9]]. Part one takes everything, and the merged interval is added after it.
    • In a gap. [[1,2],[5,6]] with [3,4] returns [[1,2],[3,4],[5,6]].
    • Inside an existing interval. [[1,5]] with [2,3] returns [[1,5]]. Taking the smaller start and the larger end is what keeps [1,5].
    • Touching on one side. [[1,4]] with [4,5] returns [[1,5]]. Using <= in part one's condition would put [1,4] into the answer separately and give [[1,4],[4,5]].
    • Touching two neighbours. [[1,2],[3,4]] with [2,3] returns [[1,4]].
    • Covering everything. [[1,2],[3,4]] with [0,10] returns [[0,10]].
    • Using < in part two. That would leave out an interval starting exactly at end, so it would survive as a separate touching interval.

    Testing

    These inputs give the following results from the reference solution:

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