Insert Interval
Insert Interval
IntervalsArrays
Problem Statement
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 ith
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).
Example
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Initial Intervals:
[1, 3]
[6, 9]
New Interval:
[2, 5]
Result:
[1, 5]
[6, 9]
Output: [[1,5],[6,9]]
Solution
The core idea is to find the correct place to insert the new interval and then merge it with any overlapping intervals.
Algorithm Steps
- Create a new list to store the merged intervals.
- Iterate through the original intervals and add all intervals that end before the new interval starts to the result list.
- Merge the new interval with any overlapping intervals. The new interval becomes the union of itself and any interval it overlaps with.
- Add the (possibly updated) new interval to the result list.
- Add all remaining intervals from the original list to the result list.
- Return the result list.
Original Intervals
[1, 2]
[3, 5]
[6, 7]
[8, 10]
[12, 16]
New Interval
[4, 8]
Result
Start: Initialize an empty result list.
Insert Interval Solution