Skip to content
Decoder

Insert Interval

Medium

Problem

intervals is sorted by start and has no overlaps. Insert new_interval into it, merging wherever needed, and return the resulting list (still sorted, still with no overlaps). Touching intervals merge.

Example 1

intervals = [[1, 3], [6, 9]], new_interval = [2, 5]

Example 2

  →  [[1, 5], [6, 9]]

Example 3

intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], new_interval = [4, 8]

Example 4

  →  [[1, 2], [3, 10], [12, 16]]

Example 5

Input
intervals = [], new_interval = [5, 7]
Output
[[5, 7]]

Constraints

  • 0 <= intervals.length <= 10^4
  • 0 <= start <= end <= 10^5 for every interval, including new_interval

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.