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 <stdio.h>
2#include <stdlib.h>
3
4struct Interval {
5 int start;
6 int end;
7};
8
9struct Interval* insert(struct Interval* intervals, int intervalsSize, struct Interval newInterval, int* returnSize) {
10 struct Interval* result = malloc(sizeof(struct Interval) * (intervalsSize + 1));
11 int i, j = 0;
12 for (i = 0; i < intervalsSize && intervals[i].end < newInterval.start; ++i) {
13 result[j++] = intervals[i];
14 }
15 for (; i < intervalsSize && intervals[i].start <= newInterval.end; ++i) {
16 newInterval.start = fmin(newInterval.start, intervals[i].start);
17 newInterval.end = fmax(newInterval.end, intervals[i].end);
18 }
19 result[j++] = newInterval;
20 while (i < intervalsSize) {
21 result[j++] = intervals[i++];
22 }
23 *returnSize = j;
24 return result;
25}
The C solution allocates memory for a new set of intervals that can hold the original intervals plus the new one. It adds all the intervals that end before the new interval's start. Next, it merges overlapping intervals with the new interval. Finally, all remaining intervals are appended after the merged intervals. The function returns the new 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.