Browse curriculum

FAANGPrep Sprint

Insert Interval

Insert a new interval into a sorted non-overlapping list.

Problem Understanding

You are given an array of non-overlapping intervals sorted by start time. Your task is to insert a new interval into this list and merge any necessary intervals to maintain the sorted, non-overlapping property.

Example:

  • Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
  • Output: [[1,5],[6,9]]
  • Why? [2,5] overlaps with [1,3]. Combining them gives [1,5].

Algorithm Strategy

Since the list is already sorted, we can solve this in O(N) time using a single pass with three phases:

  1. Skip Left: Add all intervals that come strictly before the new interval (where end < newStart).
  2. Merge Overlaps: Use a while loop to process intervals that overlap with the new one (where start <= newEnd). Continuously update the new interval to [min(start), max(end)].
  3. Append Right: Once overlaps are resolved, add the (possibly expanded) new interval, then add all remaining intervals.

Interactive Visualization

INSERT [4,8]

READY

new interval

[4,8]

new

intervals · sorted

[1,2]

[3,5]

[6,7]

[8,10]

[12,16]

result · 0

1

16

i

—

New

[4,8]

Result

0

result

Empty

 

Insert [4,8] into 5 sorted, non-overlapping intervals

Next

[1,2] ends at 2, before [4,8] starts at 4 — copy it

Intervals

New

Visualize the three-phase linear scan strategy.