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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int[][] Insert(int[][] intervals, int[] newInterval) {
6 int insertPosition = BinarySearch(intervals, newInterval[0]);
7 List<int[]> newIntervals = new List<int[]>(intervals);
8 newIntervals.Insert(insertPosition, newInterval);
9 List<int[]> mergedIntervals = new List<int[]> { newIntervals[0] };
10 for (int i = 1; i < newIntervals.Count; i++) {
11 var lastInterval = mergedIntervals[mergedIntervals.Count - 1];
12 if (lastInterval[1] >= newIntervals[i][0])
13 lastInterval[1] = Math.Max(lastInterval[1], newIntervals[i][1]);
14 else
15 mergedIntervals.Add(newIntervals[i]);
16 }
17 return mergedIntervals.ToArray();
18 }
19
20 private int BinarySearch(int[][] intervals, int start) {
21 int low = 0, high = intervals.Length;
22 while (low < high) {
23 int mid = (low + high) / 2;
24 if (intervals[mid][0] < start)
25 low = mid + 1;
26 else
27 high = mid;
28 }
29 return low;
30 }
31}
The C# approach assimilates the binary search method strategically into list operations, simplifying position determination and allowing the residues of the insertion to be effectively handled afterwards.