InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Intervals

Insert Interval

medium Original ↗ 00:00

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 so the result stays sorted by start and non-overlapping, merging newInterval with any intervals it overlaps or touches. Return the resulting list.

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

Examples

  • intervals = [[1,3],[6,9]], newInterval = [2,5][[1,5],[6,9]][2,5] overlaps [1,3], so they merge; [6,9] is unchanged.
  • intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8][[1,2],[3,10],[12,16]] — the new interval merges [3,5], [6,7], and [8,10] into one interval.
  • 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, so the intended solution uses that for a single O(n) pass instead of re-sorting.

Think about it first

Hint 1 If you ignore that the input is sorted, you could add the new interval to the list 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug