57. Insert Interval 🆕
Difficulty: Medium - Tags: Array, Intervals
Problem Statement 📜
You are given an array of non-overlapping intervals intervals where intervals[i] = [start_i, end_i] represent the start and 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.
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.
Examples 🌟
🔹 Example 1:
Input:
intervals = [[1,3],[6,9]], newInterval = [2,5]Output:
🔹 Example 2:
Input:
Output:
Explanation: The new interval [4,8] overlaps with [3,5], [6,7], and [8,10].
Constraints ⚙️
0 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^5intervalsis sorted bystart_iin ascending order.newInterval.length == 20 <= start <= end <= 10^5
Solution 💡
To solve this, we can iterate through the intervals array and:
Add intervals that come before
newIntervalwithout overlap.Merge
newIntervalwith overlapping intervals.Add intervals that come after
newIntervalwithout overlap.
Java Solution
Explanation of the Solution
Before the Overlap:
Add all intervals that end before the
newIntervalstarts.
Merging Overlapping Intervals:
For overlapping intervals, merge them by updating the start and end of
newInterval.
After the Overlap:
Add all remaining intervals after
newIntervalis inserted.
Time Complexity ⏳
O(n): We iterate through the
intervalsarray once.
Space Complexity 💾
O(n): The result array can contain up to
n + 1intervals.
You can find the full solution here.
Last updated
Was this helpful?