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.
1using System;
2using System.Collections.Generic;
3public class Solution {
4 public int[][] Insert(int[][] intervals, int[] newInterval) {
5 List<int[]> result = new List<int[]>();
6 int i = 0;
7 while (i < intervals.Length && intervals[i][1] < newInterval[0])
8 result.Add(intervals[i++]);
9 while (i < intervals.Length && intervals[i][0] <= newInterval[1]) {
10 newInterval[0] = Math.Min(newInterval[0], intervals[i][0]);
11 newInterval[1] = Math.Max(newInterval[1], intervals[i][1]);
12 i++;
13 }
14 result.Add(newInterval);
15 while (i < intervals.Length)
16 result.Add(intervals[i++]);
17 return result.ToArray();
18 }
19}
C#'s solution mirrors the logic seen in Python and Java, utilizing a List to manage result construction because Lists allow for dynamic resizing unlike standard arrays.
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.