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.
1function insert(intervals, newInterval) {
2 function findInsertPosition(arr, target) {
3 let low = 0, high = arr.length;
4 while (low < high) {
5 let mid = Math.floor((low + high) / 2);
6 if (arr[mid][0] < target) low = mid + 1;
7 else high = mid;
8 }
9 return low;
10 }
11
12 const pos = findInsertPosition(intervals, newInterval[0]);
13 intervals.splice(pos, 0, newInterval);
14 const result = [intervals[0]];
15 for (let i = 1; i < intervals.length; i++) {
16 const last = result[result.length - 1];
17 if (last[1] >= intervals[i][0])
18 last[1] = Math.max(last[1], intervals[i][1]);
19 else
20 result.push(intervals[i]);
21 }
22 return result;
23}
JavaScript provides dynamic arrays and efficient mutation methods enabling binaries to precisely adjust within the provided intervals before merging proceeds uncomplicatedly.