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.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
6 vector<vector<int>> result;
7 size_t i = 0;
8 while (i < intervals.size() && intervals[i][1] < newInterval[0])
9 result.push_back(intervals[i++]);
10 while (i < intervals.size() && intervals[i][0] <= newInterval[1]) {
11 newInterval[0] = min(newInterval[0], intervals[i][0]);
12 newInterval[1] = max(newInterval[1], intervals[i][1]);
13 i++;
14 }
15 result.push_back(newInterval);
16 while (i < intervals.size())
17 result.push_back(intervals[i++]);
18 return result;
19}
The C++ solution uses two main loops: The first loop adds intervals that do not overlap (end before the new interval's start), and the second merges overlapping intervals. After merging, the rest of the intervals are appended.
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.