Problem overview
Insert receives intervals as an int[,], one interval per row (start in column 0, end in column 1), already sorted by start with no two overlapping. It also receives newInterval, an int[] holding a start and an end. It returns the intervals after inserting the new one, merged with everything it overlaps, as an int[][] that is still sorted and overlap-free.
Intervals that only touch count as overlapping: [1,4] and [4,5] become [1,5].
For {{1,3},{6,9}} and [2,5] the result is {{1,5},{6,9}}. For {{1,2},{3,5},{6,7},{8,10},{12,16}} and [4,8] it is {{1,2},{3,10},{12,16}}: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8. With no intervals at all, inserting [5,7] gives {{5,7}}.
Approach: three groups, one pointer
You could append the new interval and run a general merge of overlapping intervals, but that needs a sort and costs O(n log n). The input is already sorted, so one pass is enough. Every existing interval falls into exactly one of three groups, in this order:
- Before. Intervals that end before the new one starts. They are copied unchanged.
- Overlapping. Intervals that overlap or touch the new one. They are all absorbed into one growing interval, whose start can only get smaller and whose end can only get larger.
- After. Intervals that start after the merged interval ends. They are copied unchanged.
One index i walks through the rows, and each group picks up where the previous one stopped. The merged interval is added between the first and third groups, which keeps the result sorted.
Step by step
- Create
result, an emptyList<int[]>, because the final size isn't known up front. - Store the row count
intervals.GetLength(0)inn, and declare the indexiat 0. - Group one: a
whileloop that runs whilei < nandintervals[i, 1] < newInterval[0]. Checki < nfirst:&&stops evaluating when it is false, so rowiis never read once the rows run out. Use<, because an interval ending exactly atnewInterval[0]touches the new one and must merge. - Copy each such row into
resultasnew int[]{intervals[i, 0], intervals[i, 1]}, then doi++. A row of anint[,]isn't an array of its own, so its two numbers are copied into a new array. - Start the growing interval:
start = newInterval[0]andend = newInterval[1]. - Group two: a
whileloop that runs whilei < nandintervals[i, 0] <= end. Every remaining interval ends at or afternewInterval[0], so it overlaps exactly when it starts byend. Use<=: touching intervals merge. Once one starts afterend, the sorted order means all the rest do too. - Widen
starttoMath.Min(start, intervals[i, 0]). - Widen
endtoMath.Max(end, intervals[i, 1]). An interval can sit entirely inside the new one, like[4,5]inside[3,9], and thenendmust stay at 9. - Advance with
i++. Without it the loop would look at the same row forever. - Add the merged interval
new int[]{start, end}toresult. If nothing overlapped,startandendare still the new interval's own values. - Group three: a
whileloop whilei < nthat copies each remaining row and doesi++. - Return
result.ToArray(), which gives anint[][].
For the second example, the first group copies [1,2], since 2 is less than 4. The second group absorbs [3,5] (start 3, end 5), then [6,7] and [8,10] (end 10), and stops at [12,16] because 12 is more than 10. The merged [3,10] is added, and the third group copies [12,16].
The solution in C#
class Solution {
public int[][] Insert(int[,] intervals, int[] newInterval) {
List<int[]> result = new List<int[]>();
int n = intervals.GetLength(0);
int i = 0;
while (i < n && intervals[i, 1] < newInterval[0]) {
result.Add(new int[]{intervals[i, 0], intervals[i, 1]});
i++;
}
int start = newInterval[0], end = newInterval[1];
while (i < n && intervals[i, 0] <= end) {
start = Math.Min(start, intervals[i, 0]);
end = Math.Max(end, intervals[i, 1]);
i++;
}
result.Add(new int[]{start, end});
while (i < n) {
result.Add(new int[]{intervals[i, 0], intervals[i, 1]});
i++;
}
return result.ToArray();
}
}
Details worth knowing:
- Short-circuit
&&. Ini < n && intervals[i, 1] < ...the second test runs only if the first is true. Swapping them would throw anIndexOutOfRangeExceptionwhenireachesn. - Input and output shapes differ. The input is a rectangular
int[,](intervals[i, 0]) and the output is a jaggedint[][](result[k][0]). The new interval is a plainint[], indexednewInterval[0]. - Empty input. An
int[,]with zero rows hasGetLength(0)equal to 0, so the three loops are skipped or end at once and only the new interval is added. List<T>needsSystem.Collections.Generic, andMathneedsSystem.
Complexity
Time: O(n). The index i only moves forward, so each interval is looked at once across the three loops. No sort is needed, because the input is already sorted.
Space: O(n) for the output list, which holds up to n + 1 intervals. Nothing else grows with the input.
Edge cases and common mistakes
- No intervals. Inserting
[5,7]gives{{5,7}}. - New interval before everything.
{{3,5}}with[1,2]gives{{1,2},{3,5}}. - New interval after everything.
{{3,5}}with[6,8]gives{{3,5},{6,8}}. - New interval inside an existing one.
{{3,9}}with[4,5]gives{{3,9}}. - New interval covering everything.
{{1,2},{5,6}}with[0,9]gives{{0,9}}. - Touching.
{{1,5}}with[5,7]gives{{1,7}}. Using<=in the first loop or<in the second would leave the two intervals separate. - Gap between neighbours.
{{1,2},{6,7}}with[3,4]gives{{1,2},{3,4},{6,7}}. - Forgetting
i++. The loop never ends.
Testing
{{1,3},{6,9}}with[2,5]gives{{1,5},{6,9}}.{{1,2},{3,5},{6,7},{8,10},{12,16}}with[4,8]gives{{1,2},{3,10},{12,16}}.- No intervals with
[5,7]gives{{5,7}}. {{1,2},{3,4}}with[5,6]gives{{1,2},{3,4},{5,6}}.{{1,5}}with[5,7]gives{{1,7}}.
