Insert Interval

35 min · insert()

Your meeting calendar is already clean and ordered. One new booking arrives; rebuilding the whole calendar from scratch would waste the structure you already have.

Given sorted, pairwise disjoint intervals and one newInterval, insert the new range, merge every overlap it creates, and return the resulting intervals in ascending start order.

Pairwise disjoint means no two existing intervals share any point. Endpoints count: if the new range ends where an existing range begins, those ranges merge.

A few ground rules:

  • Every interval has the form [start, end] with start <= end.
  • The existing intervals are sorted by start and have a strict gap between neighbors.
  • The input may contain no existing intervals at all.

Constraints

  • 0 <= intervals.length <= 100_000
  • Every interval and newInterval contains exactly two integers: [start, end].
  • intervals is sorted by ascending start and pairwise disjoint.
  • 0 <= start <= end <= 1_000_000_000
  • 0 <= newInterval[0] <= newInterval[1] <= 1_000_000_000

Hints

There are three regions

Existing intervals fall before the new range, overlap it, or fall after it. The sorted order lets you process those regions from left to right.

Copy the finished prefix

While an interval ends strictly before the new range starts, add it unchanged. The strict comparison matters because touching endpoints must merge.

Grow one combined range

While the next start is no greater than the combined end, update both boundaries. Add that combined range once, then copy the untouched suffix.

Follow-up

Can you prove that each existing interval is inspected at most once, even when the new range swallows the entire input?

Visible cases

Examples

Example 1

ready
Input
intervals = [
  [
    1,
    3
  ],
  [
    6,
    9
  ]
]
newInterval = [
  2,
  5
]
Expected
[
  [
    1,
    5
  ],
  [
    6,
    9
  ]
]
Why
the new range overlaps the first interval but stops before the second

Example 2

ready
Input
intervals = [
  [
    1,
    2
  ],
  [
    3,
    5
  ],
  [
    6,
    7
  ],
  [
    8,
    10
  ],
  [
    12,
    16
  ]
]
newInterval = [
  4,
  8
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    10
  ],
  [
    12,
    16
  ]
]
Why
one insertion bridges three existing ranges into [3, 10]

Example 3

ready
Input
intervals = []
newInterval = [
  5,
  7
]
Expected
[
  [
    5,
    7
  ]
]
Why
with no existing ranges, the new interval becomes the whole result

Interview signal

Asked at

AmazonGoogleLinkedIn
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite