InterviewPrepKit

Home / Coding / Intervals

Insert Interval

medium Original β†—
Solving tips
  • Because the input is already sorted and disjoint, the intervals overlapping newInterval form one contiguous block: answer = untouched prefix + one merged interval + untouched suffix, in a single O(n) pass.
  • Three phases: copy intervals ending strictly before ns (end < ns), absorb overlaps while start <= ne (widening ns=min, ne=max), then copy the rest.
  • Watch boundary strictness for closed intervals: touching intervals sharing an endpoint must merge, so use '<' in phase 1 and '<=' in phase 2.
  • Emit the merged interval unconditionally so the case where it sits in a gap (absorbs zero) or the input is empty still works; update BOTH ns and ne during absorption.

Problem

You are given a list of closed intervals intervals, already sorted by start and pairwise non-overlapping, plus one extra closed interval newInterval. Insert newInterval into the list so that the result is still sorted by start and still non-overlapping β€” merging newInterval with any intervals it overlaps or touches. Return the resulting list.

Intervals are closed on both ends here: [1,3] and [3,5] share the point 3 and therefore merge into [1,5].

Examples

  • intervals = [[1,3],[6,9]], newInterval = [2,5] β†’ [[1,5],[6,9]] β€” [2,5] overlaps [1,3], so they fuse; [6,9] is untouched.
  • intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] β†’ [[1,2],[3,10],[12,16]] β€” the new interval swallows [3,5], [6,7], and [8,10] into one block.
  • intervals = [], newInterval = [5,7] β†’ [[5,7]] β€” inserting into an empty list.

Constraints

  • 0 <= len(intervals) <= 10^4
  • 0 <= start <= end <= 10^5 for every interval, including newInterval
  • intervals is sorted by start and non-overlapping

The input is already sorted β€” the intended solution exploits that for a single O(n) pass rather than re-sorting.

Think about it first

Hint 1 If you were allowed to forget that the input is sorted, you could just add the new interval and solve a problem you may already know. What problem is that?
Hint 2 Walking left to right, every existing interval falls into exactly one of three groups relative to newInterval: entirely before it, overlapping it, or entirely after it. What does each group contribute to the output?
Hint 3 Copy the "entirely before" intervals as-is. Then absorb every overlapping interval by widening newInterval (take min of starts, max of ends). Emit the widened interval once, then copy the rest as-is.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.