In this approach, we'll first identify where the new interval should be inserted to maintain order. After insertion, we'll iterate over the array and merge overlapping intervals.
Time Complexity: O(n), where n is the number of intervals.
Space Complexity: O(n) due to the allocation for the result.
1def insert(intervals, newInterval):
2 result = []
3 i = 0
4 while i < len(intervals) and intervals[i][1] < newInterval[0]:
5 result.append(intervals[i])
6 i += 1
7 while i < len(intervals) and intervals[i][0] <= newInterval[1]:
8 newInterval[0] = min(newInterval[0], intervals[i][0])
9 newInterval[1] = max(newInterval[1], intervals[i][1])
10 i += 1
11 result.append(newInterval)
12 while i < len(intervals):
13 result.append(intervals[i])
14 i += 1
15 return result
16
The Python solution leverages the dynamic nature of lists. It loops through the given intervals and processes them based on their relation to the new interval, producing a merged list of intervals.
This approach optimizes finding the insert position using binary search. After inserting the new interval, it merges overlapping intervals. This is slightly more efficient when the intervals list is large.
Time Complexity: O(n), even with binary search (O(log n) for insertion, O(n) for merging).
Space Complexity: O(n), to store the new list of intervals.
1import java.util.ArrayList;
2import java.util.List;
3
4public class IntervalInsertion {
5 public int[][] insert(int[][] intervals, int[] newInterval) {
6 int pos = binarySearchPosition(intervals, newInterval[0]);
7 int[][] newIntervals = new int[intervals.length + 1][2];
8 System.arraycopy(intervals, 0, newIntervals, 0, pos);
9 newIntervals[pos] = newInterval;
10 System.arraycopy(intervals, pos, newIntervals, pos + 1, intervals.length - pos);
11 List<int[]> merged = new ArrayList<>();
12 merged.add(newIntervals[0]);
13 for (int i = 1; i < newIntervals.length; i++) {
14 int[] last = merged.get(merged.size() - 1);
15 if (last[1] < newIntervals[i][0])
16 merged.add(newIntervals[i]);
17 else
18 last[1] = Math.max(last[1], newIntervals[i][1]);
19 }
20 return merged.toArray(new int[merged.size()][]);
21 }
22
23 private int binarySearchPosition(int[][] intervals, int start) {
24 int low = 0, high = intervals.length;
25 while (low < high) {
26 int mid = low + (high - low) / 2;
27 if (intervals[mid][0] < start)
28 low = mid + 1;
29 else
30 high = mid;
31 }
32 return low;
33 }
34}
This Java solution takes advantage of binary searching and array copying to arrange intervals more efficiently pre-merge, leveraging a helper function to locate the precise index.