57. Insert Interval ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Array
, Intervals
You are given an array of non-overlapping intervals intervals
where intervals[i] = [start_i, end_i]
represent the start and 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.
Task: Insert newInterval
into intervals
such that:
The resulting intervals are sorted in ascending order by start_i
.
Merge overlapping intervals if necessary.
Return the updated list of intervals.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
Explanation: The new interval [4,8]
overlaps with [3,5]
, [6,7]
, and [8,10]
.
0 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= start_i <= end_i <= 10^5
intervals
is sorted by start_i
in ascending order.
newInterval.length == 2
0 <= start <= end <= 10^5
To solve this, we can iterate through the intervals
array and:
Add intervals that come before newInterval
without overlap.
Merge newInterval
with overlapping intervals.
Add intervals that come after newInterval
without overlap.
Before the Overlap:
Add all intervals that end before the newInterval
starts.
Merging Overlapping Intervals:
For overlapping intervals, merge them by updating the start and end of newInterval
.
After the Overlap:
Add all remaining intervals after newInterval
is inserted.
O(n): We iterate through the intervals
array once.
O(n): The result array can contain up to n + 1
intervals.
You can find the full solution .