LeetCode #57 Medium

Insert Interval

Insert Interval is LeetCode 57 (Medium). You get intervals, a list of [start, end] pairs sorted by start, where no two pairs overlap, and one more pair, newInterval. Put the new pair in, merge any pairs that now overlap, and return a list that is again sorted and overlap-free.

  • Pairs that share only an endpoint, such as [1, 3] and [3, 5], count as overlapping.
  • The list may be empty and holds up to 10⁴ pairs.
Constraints
  • 0 <= intervals.length <= 10⁴
  • intervals[i].length == 2
  • 0 <= startᵢ <= endᵢ <= 10⁵
  • intervals is sorted by startᵢ in ascending order
  • newInterval.length == 2
  • 0 <= start <= end <= 10⁵
intervalsarraygreedy
Open on LeetCode ↗
02

Intuition

Because the list is sorted and its pairs never overlap, the pairs that touch the new interval cannot be scattered. They sit in one unbroken run: every pair before the run ends too early, and every pair after it starts too late. So one left-to-right walk splits the list into three stretches:

  • Before: the pair ends before the new interval starts, so it is copied as it is.
  • Touching: the pair starts no later than the new interval's current end, so it is swallowed and the new interval stretches to cover both.
  • After: everything left over, copied as it is once the stretched interval has been placed.
How to spot this pattern

A list that is already sorted and overlap-free, plus one change to it, points to a single linear walk instead of a fresh sort.

03

Approach

Try it first

Before reading on, take [[1, 2], [3, 5], [6, 7], [8, 10]] and the new pair [4, 8]. Mark which pairs the new one reaches. Are they next to each other? What bounds do they merge into?

1

Copy the pairs that end too early

Walk from the front while the current pair ends before newInterval starts, and append each one to the answer. Such a pair cannot reach the new interval, and since the list is sorted, no pair before it can either.

2

Swallow every pair that touches

Keep lo and hi, the bounds of the growing interval. While the next pair starts at or before hi, set lo to the smaller start and hi to the larger end. Testing against the growing hi lets one long interval swallow several pairs in a row.

3

Place the merged interval once

When a pair starts after hi, or the list runs out, append [lo, hi]. Adding it only now means it goes in at its final size and in its sorted spot.

4

Copy the rest

Every pair still waiting starts after hi. They are already sorted and apart from each other, so append them unchanged.

5

Why the walk never looks back

Once a pair starts after hi, every later pair starts later still, so none of them can reach back to the merged interval. That is why one pass is enough and why the answer stays sorted without a sort.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
▶6 result = []
▶7 i, n = 0, len(intervals)
▶8 while i < n and intervals[i][1] < newInterval[0]:
▶9 result.append(intervals[i])
▶10 i += 1
▶11 lo, hi = newInterval
▶12 while i < n and intervals[i][0] <= hi:
▶13 lo = min(lo, intervals[i][0])
▶14 hi = max(hi, intervals[i][1])
▶15 i += 1
▶16 result.append([lo, hi])
▶17 while i < n:
▶18 result.append(intervals[i])
▶19 i += 1
▶20 return result
newlist2–51–36–9012345678910answernew interval 2–5: walk the list from the left
newInterval2–5
The list is sorted and its pairs never overlap, so the pairs this new interval touches sit next to each other. One walk from the left finds them.
newlist1–51–36–9012345678910answer1–3 overlaps 2–5 → stretch to 1–5
pair1–3
lo1
hi5
This pair starts at 1, no later than the growing interval's end, 5, so the two merge. The bounds become the smaller start and the larger end: 1–5.
newlist1–51–36–9012345678910answer6–9 starts after 5 → stop merging
pair6–9
hi5
This pair starts at 6, past the merged end 5. Every later pair starts even later, so nothing else can reach the merged interval.
newlist1–51–36–9012345678910answer1–5place 1–5 in the answer
placed1–5
The merged interval has reached its final size, and every pair before it is already in the answer, so it goes in now, in its sorted spot.
newlist1–51–36–9012345678910answer1–56–96–9 is after the merge → copy it
pair6–9
answer size2
Pairs after the merged interval were already sorted and apart from each other, so each one is copied without a check.
newlist1–51–36–9012345678910answer1–56–9answer: 2 pairs, sorted, none overlap
answer1–5, 6–9
Every pair was looked at once. The answer is [1, 5], [6, 9], still sorted and overlap-free.
05

Common pitfalls

Leaving pairs that share an endpoint apart

✗ Wrong
while i < n and intervals[i][0] < hi:
✓ Right
while i < n and intervals[i][0] <= hi:

A shared endpoint counts as overlap. On [[1, 3], [5, 7]] with [2, 5], the strict test stops at [5, 7] and returns [[1, 5], [5, 7]] instead of [[1, 7]].

Stretching only the right end

✗ Wrong
hi = max(hi, intervals[i][1])
✓ Right
lo = min(lo, intervals[i][0])
hi = max(hi, intervals[i][1])

The first pair swallowed can start before the new interval does. With [[3, 5]] and [4, 8] the answer is [[3, 8]], but moving only hi returns [[4, 8]].

06

Edge cases

Empty list, e.g. [] with [5, 7]

Both copy loops and the swallow loop do nothing, so the answer is just [[5, 7]].

New pair before every other pair, e.g. [[3, 4]] with [1, 2]

Nothing is copied first and nothing is swallowed, so [1, 2] lands at the front.

New pair inside one pair, e.g. [[1, 9]] with [3, 4]

[1, 9] is swallowed, lo and hi become 1 and 9, and the list comes back as it was.

07

Complexity

Time
O(n)
Space
O(n)
Each pair is looked at once. The answer holds up to n + 1 pairs; besides it, only lo, hi and the index are kept.
08

Insert Interval FAQ

Can I add the new pair, sort, and merge instead?

Yes, and it gives the right answer: it is the Merge Intervals method (LeetCode 56). It costs O(n log n) for the sort, which redoes an ordering the input already gives you for free.

Does binary search make it faster?

Binary search finds where the touching run starts and ends in O(log n). The answer is still a list of up to n + 1 pairs, though, so building it costs O(n) either way. It only helps when the list lives in a structure that can cut out a run cheaply, such as a balanced tree.