Start learning free

LESSON 269 OF 321 · INTERVALS

Insert Interval in Python: One Pass in O(n) with Three Loops

Practice O(n) Read the full explanation

You get a list 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 a list 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

    PYTHON · INTERVALS

    Insert Interval in Python, explained

    Problem overview

    The method insert receives intervals, a list of [start, end] lists 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 resulting list, still sorted and with no overlaps. Intervals that touch, like [1, 4] and [4, 5], share the point 4, so they merge. The list can be empty, and the statement asks for O(n) time.

    For intervals = [[1, 3], [6, 9]] and newInterval = [2, 5] the result is [[1, 5], [6, 9]]: [2, 5] overlaps [1, 3], and [6, 9] starts after 5.

    Approach: before, overlapping, after

    Because the list is sorted and has no overlaps, there is no need to sort again or to compare every pair. The intervals fall into three groups, in this order:

    1. those that end before newInterval starts: they go into the answer unchanged;
    2. those that overlap it: they all merge with it into a single interval;
    3. those that start after the merged interval ends: they go in unchanged too.

    One index i walks through the list once, and each group's loop picks up where the previous one stopped, so the work is O(n). Merging after a full sort, as in the general merge problem, would cost O(n log n).

    A simpler idea is to append newInterval to the list, sort everything and merge as in the general merge problem. That works, but it ignores the guarantee that the input is already in order, and it pays O(n log n) for the sort. The three-group split uses the guarantee: each group is a contiguous run of the list, so a plain index is all the bookkeeping needed. The only subtle part is the boundary between groups, which is decided by the two comparisons: an interval is "before" when it ends strictly earlier than the new start, and it is "overlapping" when it starts no later than the current end.

    Step by step

    1. Create an empty list result.
    2. Store len(intervals) in n and start an index i at 0.
    3. Part one: a while loop that runs while i < n and intervals[i][1] < newInterval[0]. Use <: an interval that ends exactly where the new one starts touches it, so it belongs to the merge. Check i < n first, because and stops there when the intervals run out, before intervals[i] is read.
    4. Inside it, append intervals[i] to result and do i += 1.
    5. Part two: set start, end = newInterval[0], newInterval[1], a growing interval that every overlapping interval can only widen.
    6. Loop while i < n and intervals[i][0] <= end. Every interval left ends at or after newInterval[0], so it overlaps the growing interval exactly when it starts by end. Use <=, since touching counts. The list is sorted, so once an interval starts after end, all the rest do too.
    7. Set start to min(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one.
    8. Set end to max(end, intervals[i][1]). An interval can lie completely inside the new one, like [4, 5] inside [3, 9], and then end must stay 9.
    9. Do i += 1. Without it the loop would look at the same interval forever.
    10. Append [start, end] to result after the loop. It goes after the part-one intervals and before the part-three ones, which keeps the result sorted. If nothing overlapped, start and end are still the new interval's own values.
    11. Part three: a while loop that runs while i < n. Every interval left starts after end.
    12. Append intervals[i] and do i += 1, as in part one.
    13. Return result.

    The solution in Python

    class Solution:
        def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
            result = []
            n = len(intervals)
            i = 0
            while i < n and intervals[i][1] < newInterval[0]:
                result.append(intervals[i])
                i += 1
            start, end = newInterval[0], newInterval[1]
            while i < n and 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
    

    On intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]] and newInterval = [4, 8], part one copies [1, 2] and stops at [3, 5], because 5 is not less than 4. Part two then widens the growing interval: [3, 8] after [3, 5], still [3, 8] after [6, 7], and [3, 10] after [8, 10], which touches it at 8. Part three copies [12, 16]. The result is [[1, 2], [3, 10], [12, 16]].

    Python details worth knowing:

    • and short-circuits. In i < n and intervals[i][1] < ... the second test only runs when the first is true, which protects against an IndexError at the end of the list.
    • Tuple assignment. start, end = newInterval[0], newInterval[1] creates both variables in one line. start, end = newInterval would work too for a two-item list.
    • Shared inner lists. Parts one and three append the input's own inner lists, not copies. If you change an inner list of the result, such as result[0][0] = 99, the same list in intervals changes too. The merged interval is a new list.
    • min and max return the smaller or larger of their arguments.

    Complexity

    Time: O(n): i only moves forward and each interval is looked at by exactly one loop. Space: O(n) for result, which holds up to n + 1 intervals.

    Edge cases and common mistakes

    • Empty list. intervals = [] with newInterval = [5, 7] gives [[5, 7]]: all three loops end at once.
    • New interval inside an existing one. [[1, 5]] with [2, 3] gives [[1, 5]].
    • New interval first or last. [[3, 5]] with [0, 1] gives [[0, 1], [3, 5]], and with [7, 8] gives [[3, 5], [7, 8]].
    • Touching on both sides. [[1, 2], [3, 4]] with [2, 3] gives [[1, 4]].
    • Fitting in a gap. [[1, 2], [5, 6]] with [3, 4] gives [[1, 2], [3, 4], [5, 6]].
    • Wrong comparison. Writing <= in the first loop or < in the second leaves touching intervals unmerged.
    • Forgetting i += 1. A while loop without it 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, 5]], [2, 3] gives [[1, 5]].
    • [[1, 2], [3, 4]], [2, 3] gives [[1, 4]].
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free