Insert Interval - Problem

You are given an array of non-overlapping intervals intervals where intervals[i] = [start_i, end_i] represent the start and the end of the i-th interval and intervals is sorted in ascending order by start_i.

You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by start_i and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

Input & Output

Example 1 — Basic Overlap
$ Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
💡 Note: newInterval [2,5] overlaps with [1,3], so we merge them to [1,5]. The interval [6,9] doesn't overlap, so it remains unchanged.
Example 2 — Multiple Overlaps
$ Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
💡 Note: newInterval [4,8] overlaps with [3,5], [6,7], and [8,10], so we merge them all into [3,10]. Intervals [1,2] and [12,16] remain separate.
Example 3 — No Overlap
$ Input: intervals = [[1,5]], newInterval = [6,8]
Output: [[1,5],[6,8]]
💡 Note: newInterval [6,8] doesn't overlap with [1,5] since 6 > 5, so we simply add it to the end.

Constraints

  • 0 ≤ intervals.length ≤ 104
  • intervals[i].length == 2
  • 0 ≤ starti ≤ endi ≤ 105
  • intervals is sorted by starti in ascending order
  • newInterval.length == 2
  • 0 ≤ start ≤ end ≤ 105

Visualization

Tap to expand
Insert Interval: Merge Overlapping Time SlotsInput intervals:[1,3][6,9]New interval:[2,5]Timeline Visualization:0246810[1,3][2,5][6,9]Overlap detected: [1,3] ∩ [2,5] = [2,3]Result after merge:[1,5][6,9]Output: [[1,5],[6,9]]
Understanding the Visualization
1
Input
Sorted non-overlapping intervals + new interval to insert
2
Process
Find overlaps and merge intervals while maintaining sorted order
3
Output
New sorted array with merged intervals
Key Takeaway
🎯 Key Insight: Process intervals in three phases - before, overlapping, and after the new interval
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
125.0K Views
High Frequency
~25 min Avg. Time
3.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen