Problem
You are given a list of non-overlapping intervals sorted by start, and a new interval. Insert the new interval, merging if needed, and return the resulting list.
Original: LeetCode 57: Insert Interval.
Examples
Example 1
`intervals = [[1, 3], [6, 9]], newInterval = [2, 5]``[[1, 5], [6, 9]]`Example 2
`intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval = [4, 8]``[[1, 2], [3, 10], [12, 16]]`Constraints
0 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^5intervalsis sorted bystartiin ascending order.newInterval.length == 20 <= start <= end <= 10^5
Hints
Hint 1
The existing intervals do not overlap. The new interval may overlap several of them, or sit completely to the left or the right.
Hint 2
This is Merge Intervals with a single insertion into an already-sorted list, so one linear scan is enough.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Append the new interval and call Merge Intervals, which re-sorts.
Optimal. Three-phase walk: take intervals that are completely before, merge the overlapping stretch, then take the intervals that are completely after.
Alternative. Binary search for the first overlapping interval, then scan only the overlap region, which is useful when n is large and overlap is rare.
Complexity
- Time
- O(n)
O(n) time and O(n) space for the output.
- Space
- O(n)
Code
def insert(intervals: list[list[int]], new_interval: list[int]) -> list[list[int]]:
out: list[list[int]] = []
i, n = 0, len(intervals)
while i < n and intervals[i][1] < new_interval[0]:
out.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= new_interval[1]:
new_interval[0] = min(new_interval[0], intervals[i][0])
new_interval[1] = max(new_interval[1], intervals[i][1])
i += 1
out.append(new_interval)
out.extend(intervals[i:])
return out
if __name__ == "__main__":
assert insert([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]]
assert insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]) == [[1, 2], [3, 10], [12, 16]]
print("ok")import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InsertInterval {
static int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> out = new ArrayList<>();
int i = 0, n = intervals.length;
while (i < n && intervals[i][1] < newInterval[0]) out.add(intervals[i++]);
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
out.add(newInterval);
while (i < n) out.add(intervals[i++]);
return out.toArray(new int[0][]);
}
public static void main(String[] args) {
int[][] a = insert(new int[][] {{1, 3}, {6, 9}}, new int[] {2, 5});
if (!Arrays.deepEquals(a, new int[][] {{1, 5}, {6, 9}})) throw new AssertionError(Arrays.deepToString(a));
int[][] b = insert(new int[][] {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}}, new int[] {4, 8});
if (!Arrays.deepEquals(b, new int[][] {{1, 2}, {3, 10}, {12, 16}})) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: insert [2,5] into [[1,3],[6,9]] yields [[1,5],[6,9]]; insert [4,8] into [[1,2],[3,5],[6,7],[8,10],[12,16]] yields [[1,2],[3,10],[12,16]].
- A new interval that sits after every existing interval is just appended.
Follow-ups
- My Calendar I asks you to reject the insertion when it would overlap, instead of merging.
Interview script
"The list is already sorted and disjoint, so I copy the intervals that end before the new start, merge everything that overlaps the new interval, and then copy the rest. One pass, no extra sort."
Source: LeetCode 57: Insert Interval
Greedy scheduling
Sources (1)
- LeetCode 57: Insert Intervalleetcode.com