Insert Interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. 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 `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` after the insertion.
Examples
Constraints
0 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^5intervals is sorted by starti in ascending order.newInterval.length == 20 <= start <= end <= 10^5
Iterative Merge
Approach
We iterate through the given intervals and compare each with `newInterval`. There are three cases: 1. The current interval ends before `newInterval` starts: It is strictly before `newInterval`, so we add it to the result. 2. The current interval starts after `newInterval` ends: It is strictly after `newInterval`. We can add `newInterval` to the result (if we haven't already), and then add the current interval. 3. The intervals overlap: We merge them by updating `newInterval` to be `[min(start1, start2), max(end1, end2)]`. After the loop, we might still need to add `newInterval` if it was merged until the very end or if it's after all original intervals.
Complexity Analysis
Time complexity is O(n) because we iterate through the array once. Space complexity is O(n) to store the result list.
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> res = new ArrayList<>(); for (int[] interval : intervals) { // Case 1: current interval is strictly before newInterval if (interval[1] < newInterval[0]) { res.add(interval); } // Case 2: current interval is strictly after newInterval else if (interval[0] > newInterval[1]) { res.add(newInterval); newInterval = interval; // The current interval becomes the "new" one to add later } // Case 3: overlap, merge them else { newInterval[0] = Math.min(newInterval[0], interval[0]); newInterval[1] = Math.max(newInterval[1], interval[1]); } } // Add the last merged interval res.add(newInterval); return res.toArray(new int[res.size()][]); }}