15% off all plans & roadmaps Use code

See plans

Insert Interval

Updated

TL;DR: You add one interval to a sorted list of disjoint intervals and merge whatever it touches. Because the list is already sorted, one left-to-right pass in three phases does it in O(n).

Problem

You are given an array of non-overlapping intervals intervals, where intervals[i] = [starti, endi] gives the start and end of the ith interval. The array is sorted in ascending order by starti. You are also given an interval newInterval = [start, end].

Insert newInterval into intervals so that the array stays sorted by starti and still has no overlapping intervals. Merge intervals where necessary. Return intervals after the insertion.

You do not need to modify intervals in place. You can build and return a new array.

Example 1

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: the new interval [4,8] overlaps with [3,5], [6,7] and [8,10], so all four merge into [3,10].

Constraints

  • 0 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10^5
  • intervals is sorted by starti in ascending order.
  • newInterval.length == 2
  • 0 <= start <= end <= 10^5

Constraints that matter

  • intervals.length is at most 10^4, so even O(n log n) passes easily. The real goal is to use the sorted order and reach O(n).
  • intervals is already sorted by start and has no overlaps. That guarantee lets you split the list into a left group, a middle group and a right group with no sorting.
  • intervals.length can be 0, so your code must handle an empty list and still return [newInterval].
  • Values go up to 10^5 and fit easily in a 32-bit int, so there is no overflow risk in any language.
  • starti <= endi for every interval, so no interval is inverted and min and max merging is safe.

View on LeetCode

Hints

Hint 1

This is the interval merging pattern with a greedy sweep.

Hint 2

Ignore the fact that the list is already sorted.

Solution

Intuition

This is the interval merging pattern with a greedy sweep. The input is sorted and disjoint, so every existing interval sits in exactly one of three places relative to the new one: entirely to its left, overlapping it, or entirely to its right. Those three groups appear in that order in the list.

Picture a wall calendar of non-overlapping meetings already in order. The sticky note is your new meeting: you stretch it over every meeting it touches, then copy the untouched meetings before and after as they are.

What to notice: the list is sorted by start, and no two intervals overlap, so ends are sorted too. An interval that ends before the new one starts can never matter again. An interval that starts after the new one ends can never matter either. Only the contiguous middle block needs real work.

Why a single pass works: while you scan the middle block, you grow the new interval to cover each overlapping neighbor. Growing it takes the smaller start and the larger end. Once you reach an interval that starts after the grown interval ends, nothing further right can touch it, because later starts are even larger. You never go back.

Two intervals overlap when a.start <= b.end and b.start <= a.end. Touching at a single point counts, so [1,2] and [2,3] merge into [1,3]. The left test is therefore a strict end < newStart, and the middle test is start <= newEnd.

Watch the pattern animation

Worked example

Input: intervals = [], newInterval = [5, 7]
Output: [[5, 7]]
Explanation: The list is empty, so nothing can overlap the new interval. The answer is the new interval alone, wrapped in a list.

Approach 1: Brute force: append, sort, merge

Ignore the fact that the list is already sorted. Treat the task as the general merge-intervals problem. Add the new interval to the list, sort everything by start, then sweep once and merge any interval whose start is at most the end of the last merged one.

This is correct for any input order, which is why it is the baseline. It is also the first thing most people write.

Steps

  1. Copy intervals into a new list and append newInterval.
  2. Sort the new list by start value.
  3. Create an empty result list.
  4. For each interval in sorted order, check whether result is non-empty and its last end is at least the current start.
  5. If so, set the last end in result to the larger of the two ends. Otherwise append a copy of the current interval.
  6. Return result.

Dry run

On intervals = [], newInterval = [5, 7]:

  1. The combined list is [[5,7]].
  2. Sorting one element changes nothing.
  3. result is empty, so [5,7] is appended.
  4. The sweep ends and the function returns [[5,7]].

On a larger input such as [[1,3],[6,9]] plus [2,5], sorting gives [[1,3],[2,5],[6,9]]. The sweep merges [1,3] and [2,5] into [1,5], then appends [6,9].

Complexity

TimeO(n log n)
SpaceO(n)

Here n is the number of existing intervals. The combined list has n + 1 items and sorting it costs O(n log n). The merge sweep visits each item once for O(n) extra, so sorting dominates. The sorted copy and the result list each hold at most n + 1 intervals, which gives O(n) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        items = intervals + [newInterval]
        items.sort(key=lambda x: x[0])
        result = []
        for s, e in items:
            if result and result[-1][1] >= s:
                # overlaps the last merged interval: extend its end
                result[-1][1] = max(result[-1][1], e)
            else:
                result.append([s, e])
        return result
Interval Merging/Scheduling pattern infographic for Insert Interval

Solution pattern

Interval Merging/Scheduling

Part of Greedy Patterns

Approach 2: One-pass three-phase scanOptimalInterval Merging/Scheduling

What's slow: the sort. It reorders a list that was already in order, and it costs O(n log n) to learn nothing new. The only unsorted item is the new interval, and you know where it belongs by comparing it with neighbors.

The insight that fixes it: split the scan into three phases that follow the sorted order. First copy every interval that ends before the new one starts. Then absorb every interval that starts at or before the new interval's current end, widening the new interval each time. Finally copy what is left. Each interval is touched once.

Steps

  1. Create result, set i = 0, and read start and end from newInterval into local variables.
  2. Phase 1: while i < n and intervals[i][1] < start, append intervals[i] to result and advance i.
  3. Phase 2: while i < n and intervals[i][0] <= end, set start = min(start, intervals[i][0]) and end = max(end, intervals[i][1]), then advance i.
  4. Append [start, end] to result.
  5. Phase 3: while i < n, append intervals[i] to result and advance i.
  6. Return result.

Dry run

Trace on intervals = [], newInterval = [5, 7]. Here n = 0, so every loop guard i < n fails at once.

StepActionistartendresult
0Initialize, read [5,7]057[]
1Phase 1 check: 0 < 0 is false, skip057[]
2Phase 2 check: 0 < 0 is false, skip057[]
3Append [start, end]057[[5,7]]
4Phase 3 check: 0 < 0 is false, skip057[[5,7]]
5Return057[[5,7]]

The output is [[5,7]], which matches the expected answer.

For a case that exercises all phases, take [[1,2],[3,5],[6,7],[8,10],[12,16]] with [4,8]. Phase 1 copies [1,2] because 2 < 4. Phase 2 absorbs [3,5] (start 3, end 8), [6,7] (no change) and [8,10] (end 10), giving [3,10].

[12,16] starts at 12, which is greater than 10, so phase 2 stops. Phase 3 copies [12,16]. The result is [[1,2],[3,10],[12,16]].

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of existing intervals. The index i only moves forward and is shared by all three loops, so each interval is examined once and the total work is O(n). Auxiliary space beyond the output is O(1), but the returned list holds up to n + 1 intervals, so counting the output gives O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        result = []
        i, n = 0, len(intervals)
        start, end = newInterval[0], newInterval[1]

        # Phase 1: intervals that finish before the new one starts
        while i < n and intervals[i][1] < start:
            result.append(intervals[i])
            i += 1

        # Phase 2: intervals that overlap, absorbed into [start, end]
        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])

        # Phase 3: intervals that begin after the merged one ends
        while i < n:
            result.append(intervals[i])
            i += 1
        return result

Common mistakes

  • Using intervals[i][1] <= start in phase 1. An interval that ends exactly where the new one starts touches it and must merge. Use a strict < in phase 1 and <= in phase 2.
  • Using intervals[i][0] < end in phase 2. That skips an interval starting exactly at end, so [8,10] would not merge with [4,8]. Write <=.
  • Appending [start, end] inside the phase 2 loop. You would emit a partial interval for every overlap. Append once, after the loop finishes.
  • Forgetting the i < n guard in a while loop. When the new interval is larger than every existing one, intervals[i] reads past the end. Put i < n first in every condition.
  • Only taking end = max(end, intervals[i][1]) and leaving start alone. The first overlapping interval can start earlier than the new one, as [1,3] does for [2,5]. Update both bounds with min and max.
  • Sorting the whole list again after the pass, or inserting in the middle of an array. Both add cost the sorted input already saved you. Build a fresh result list in order.

Edge cases

  • intervals = [], newInterval = [5,7]: no loop runs, and the output is [[5,7]].
  • The new interval lies entirely left of all others, for example [[3,4]] with [1,2]: phase 1 copies nothing, and the output is [[1,2],[3,4]].
  • The new interval lies entirely right of all others, for example [[1,2]] with [5,6]: phase 1 copies [1,2], and the output is [[1,2],[5,6]].
  • The new interval touches an end point, for example [[1,2],[4,5]] with [2,4]: all three merge into [[1,5]].
  • The new interval swallows everything, for example [[2,3],[5,6]] with [0,10]: the output is [[0,10]].
  • The new interval sits inside one existing interval, for example [[1,10]] with [3,4]: start stays 1, end stays 10, and the output is [[1,10]].
  • The new interval is a single point, for example [[1,5]] with [5,5]: it overlaps at 5, and the output is [[1,5]].

Follow-ups interviewers ask

The list is sorted, so can you find the merge range faster than a linear scan?
Yes, partly. Binary search for the first interval whose end is at least newInterval.start, and for the last interval whose start is at most newInterval.end. Those two indices bound the overlap block in O(log n). You still have to copy the left and right groups into the output, so building the answer is O(n). If you could edit the array in place, such as in a linked list, the search would dominate.
How would you insert into a structure that you update many times?
A sorted list rebuilt per insert costs O(n) each time. Use a balanced tree or an ordered map keyed by start. Find the neighbors in O(log n), remove the overlapping ones, and insert the merged interval. Each removed interval was inserted once, so the amortized cost stays O(log n) per insert.
What changes if the input intervals are not sorted?
The three-phase scan no longer works because overlapping intervals can be anywhere. Fall back to the first approach: append the new interval, sort by start, and merge in one sweep for O(n log n). Alternatively, one linear pass can still work. Keep intervals that do not touch the new one in the output, merge the ones that do, then sort the output once.

Insert Interval FAQ

What is the time complexity of Insert Interval?

The optimal scan is O(n), where n is the number of existing intervals. The shared index moves forward through three loops and never goes back. The sort-and-merge baseline is O(n log n) because of the sort.

Why use a greedy three-phase scan for Insert Interval?

The input is sorted and disjoint, so intervals fall into left, overlapping and right groups in that order. You can decide each interval's fate by comparing it with the current new interval, with no need to look back. That removes the sort and gives a single O(n) pass.

Can Insert Interval be solved in O(1) extra space?

Only if you count the output as free. Beyond the returned list, the scan keeps only i, start and end. The answer itself can hold n + 1 intervals, so building a new list costs O(n) space. An in-place version would need to shift array elements, which costs O(n) time per insert.

Do adjacent intervals like [1,2] and [2,3] merge in Insert Interval?

Yes. They share the point 2, so they overlap and become [1,3]. That is why phase 1 uses end < start strictly and phase 2 uses start <= end. Intervals like [1,2] and [3,4] have a gap and stay separate.

Can I use binary search for Insert Interval in Python or Java?

You can. Use bisect in Python or Arrays search logic in Java to find the first overlapping index and the last one. Then slice the list and build the result. It lowers the search cost to O(log n), but the total stays O(n) because copying the output takes linear time. The linear scan is shorter and has fewer off-by-one risks.

How is Insert Interval different from Merge Intervals (LeetCode 56)?

Merge Intervals gives you an unsorted list, so you must sort first for O(n log n). Insert Interval gives you a sorted, disjoint list plus one extra interval, so a linear pass is enough. The merge rule inside the overlap phase is the same.

Asked at

See which companies ask this — Pro

Practise it