Problem overview
The method insert receives an int[][] named intervals, sorted by start with no two intervals overlapping, and an int[] named newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result as an int[][], still sorted and with no overlaps. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they merge into [1,5].
For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1, 5], [6, 9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] the result is [[1, 2], [3, 10], [12, 16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so all four become [3,10]. With intervals = [] and [5,7] the result is [[5, 7]]. The statement asks for O(n) time.
Approach: before, overlapping, after
The input is already sorted, so there is no need to sort again, which would cost O(n log n). The existing intervals fall into three groups, in this order:
- Before. They end before
newIntervalstarts. They go into the answer unchanged. - Overlapping. They start no later than the growing merged interval ends. Each one can only widen the new interval: an earlier start or a later end. All of them collapse into one interval.
- After. They start after the merged interval ends. They go into the answer unchanged.
One index i walks through the array exactly once, and each group's loop picks up where the previous one stopped. The merged interval is added between groups one and three, so the result stays sorted by start.
Take the second example, [4,8] against [[1,2],[3,5],[6,7],[8,10],[12,16]]. [1,2] ends at 2, before 4, so it is copied. [3,5] starts at 3, which is no later than 8, so the loop merges it: the start stays 3 (the smaller of 4 and 3) and the end stays 8 (the larger of 8 and 5). [6,7] and [8,10] start at 6 and 8, both no later than 8, so they merge too, and the end becomes 10. [12,16] starts at 12, after 10, so it is copied. The result is [[1, 2], [3, 10], [12, 16]], as listed above.
Step by step
- Create
result, aList<int[]>backed by a newArrayList, since its final size isn't known. - Store
n, the number of intervals, and declare the indexistarting at 0. All three parts share it. - Part one, the loop. Run while
i < nandintervals[i][1] < newInterval[0]. Use<: an interval ending exactly atnewInterval[0]touches the new one, and touching intervals merge. Testi < nfirst, so&&stops before reading past the end of the array. - Copy and advance. Add
intervals[i]toresultand doi++. - Part two, the variables. Declare
start = newInterval[0]andend = newInterval[1]. They hold the growing merged interval. - The overlap loop. Run while
i < nandintervals[i][0] <= end. Every interval left ends at or afternewInterval[0], so it overlaps exactly when it starts byend. The sort order means that once one fails the test, all the rest do too. - Widen the start with
Math.min(start, intervals[i][0]). - Widen the end with
Math.max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside, like[4,5]inside[3,9]. - Advance with
i++, or the loop would look at the same interval forever. - Add the merged interval as
new int[]{start, end}. If nothing overlapped, it isnewIntervalunchanged. - Part three, the loop. Run while
i < n. - Copy the rest with
result.add(intervals[i])andi++. - Return
result.toArray(new int[0][]), which copies the list into an array of arrays of the right size.
The solution in Java
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new ArrayList<>();
int n = intervals.length;
int i = 0;
while (i < n && intervals[i][1] < newInterval[0]) {
result.add(intervals[i]);
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(intervals[i]);
i++;
}
return result.toArray(new int[0][]);
}
}
Java details worth noticing:
- Imports.
ListandArrayListlive injava.util. Outside the lesson's editor the file needsimport java.util.*;. - Multiple declarations on one line.
int start = newInterval[0], end = newInterval[1];declares twointvariables, each with its own initializer. - Short-circuit
&&. The right side runs only when the left side is true. That is whyi < nmust come first. Reversed, the loop would throwArrayIndexOutOfBoundsExceptionafter the last interval. - Rows are shared with the input.
result.add(intervals[i])adds the sameint[]object, not a copy. That is fine, since nothing here changes it, but a caller who later edits the returned rows would also change the input's rows. toArray(new int[0][]). The empty array gives the element type,int[], and the method returns anint[][]of the right length. AList<int[]>can't useint[][]directly because generics hold objects, and arrays are objects.
Complexity
Time: O(n). The index i only moves forward, and the three loops together advance it at most n times. The calls to add are constant time on average.
Space: O(n) for the result, which holds up to n + 1 intervals. Apart from the output, only a few integers are used.
Edge cases and common mistakes
- Empty input. With
[]and[5,7], none of the loops runs, and the merged interval is[5,7], giving[[5, 7]]. - The new interval goes first.
[[3,4]]with[1,2]gives[[1, 2], [3, 4]]: part one copies nothing, the new interval is added, and part three copies[3,4]. - The new interval goes last.
[[1,2]]with[5,6]gives[[1, 2], [5, 6]]. - An interval around the new one.
[[3,9]]with[4,5]gives[[3, 9]]. The start and end both keep[3,9]'s values, because of the min and the max. - Touching intervals. Using
<=in the first loop or<in the second would leave touching intervals apart. The statement says they merge. - Setting
endinstead of taking the max. An interval inside the new one would shrink the end. - Forgetting
i++. Any of the three loops would run forever.
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]].[]with[5,7]gives[[5, 7]].[[3,4]]with[1,2]gives[[1, 2], [3, 4]].[[1,2]]with[5,6]gives[[1, 2], [5, 6]].[[3,9]]with[4,5]gives[[3, 9]].
