Insert Interval - Problem

You are given an array of non-overlapping intervals where each interval is represented as [start, end]. The intervals are already sorted by their start times in ascending order.

Your task is to insert a new interval into this array while maintaining the sorted order and ensuring no intervals overlap. If the new interval overlaps with existing intervals, you must merge them into a single interval.

Goal: Return the updated array of intervals after inserting the new interval.

Example: If you have intervals [[1,3],[6,9]] and want to insert [2,5], the result should be [[1,5],[6,9]] because [1,3] and [2,5] overlap and merge into [1,5].

Input & Output

example_1.py โ€” Basic Insertion
$ Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
โ€บ Output: [[1,5],[6,9]]
๐Ÿ’ก Note: The new interval [2,5] overlaps with [1,3], so they merge into [1,5]. The interval [6,9] doesn't overlap, so it remains unchanged.
example_2.py โ€” Multiple Merges
$ Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
โ€บ Output: [[1,2],[3,10],[12,16]]
๐Ÿ’ก Note: The new interval [4,8] overlaps with [3,5], [6,7], and [8,10]. All these intervals merge into [3,10].
example_3.py โ€” Insert at Beginning
$ Input: intervals = [[3,5],[6,9]], newInterval = [1,2]
โ€บ Output: [[1,2],[3,5],[6,9]]
๐Ÿ’ก Note: The new interval [1,2] doesn't overlap with any existing intervals and comes before all of them, so it's inserted at the beginning.

Visualization

Tap to expand
๐Ÿ“… Conference Room SchedulingExisting bookings:9-11 AM2-4 PM6-8 PMNew meeting request:1-7 PMAfter scheduling:9-11 AM1-8 PM(merged)โœ“ Keep 9-11 AM (no conflict)โœ“ Merge 1-7 PM with 2-4 PM and 6-8 PMโœ“ Result: Three time slots become two
Understanding the Visualization
1
Scan Early Meetings
Copy all meetings that end before your new meeting starts
2
Handle Conflicts
Merge your new meeting with all overlapping existing meetings
3
Copy Remaining
Add all later meetings that don't conflict with the merged meeting
Key Takeaway
๐ŸŽฏ Key Insight: Process intervals in three distinct phases to achieve optimal O(n) time complexity while maintaining the sorted order property.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through all intervals, each interval processed once

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

O(n) space for the result array, no additional data structures needed

n
2n
โšก Linearithmic Space

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
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
39.2K Views
High Frequency
~15 min Avg. Time
1.5K 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