All coding questions

Insert Interval

medium
NeetCode 150intervalsarrays

Problem

Given a list of non-overlapping intervals sorted by start and a new interval, insert it and merge any overlaps so the result stays sorted and non-overlapping.

Examples

Input: intervals = [[1, 3], [6, 9]], new = [2, 5]
Output: [[1, 5], [6, 9]]
The new interval merges with [1, 3].

Constraints

  • 0 <= intervals.length <= 10^4
  • Intervals are sorted and non-overlapping
Hints(tap to reveal)
  • 1. Add all intervals ending before the new one starts.
  • 2. Then absorb every overlapping interval into the new one.
Optimal approach(spoiler)
  1. Append all intervals strictly before the new interval unchanged.
  2. Merge every interval overlapping the new one by widening its bounds.
  3. Append the merged new interval once overlaps end.
  4. Append the remaining intervals untouched.
  5. O(n) time, O(n) output space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor