Problem overview
The function insert receives intervals, an Array<IntArray> of [start, end] pairs that is already sorted by start and has no overlaps, and one more pair, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result as an Array<IntArray>, still sorted and without overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5]. The statement asks for O(n) time, where n is the number of intervals, which can reach 100,000.
For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1,5],[6,9]]. For intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] and newInterval = [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. With intervals = [] and newInterval = [5,7] the result is [[5,7]].
Approach: before, overlapping, after
Because the input is already sorted, there is no need to sort it again, which would cost O(n log n). Walking through the list once, every existing interval falls into one of three groups, in this order:
- Before. The interval ends before the new interval starts. It can't touch the new one and goes into the answer unchanged.
- Overlapping. The interval starts no later than the end of the new interval, and it isn't in the first group, so it ends at or after the new interval's start. All of these merge with the new interval into one. Each can only widen it, with an earlier start or a later end.
- After. The interval starts after the end of the merged interval, and so does every later one, because the list is sorted. They go into the answer unchanged.
The merged interval is added between the first and the third group, so the result stays sorted. If nothing overlaps, the merged interval is just newInterval, and it lands in its correct place.
Here is how the second example moves through the three parts:
part 1 keeps [1, 2]
part 2 merges [3, 5] -> [3, 8]
part 2 merges [6, 7] -> [3, 8]
part 2 merges [8, 10] -> [3, 10]
part 3 keeps [12, 16]
Step by step
- Create
resultas an emptymutableListOf<IntArray>(). Its size isn't known up front. - Store
intervals.sizeinnand create an indexvar i = 0. All three loops sharei, and each continues where the last one stopped. - Part one loop:
while (i < n && intervals[i][1] < newInterval[0]). Use<, because an interval that ends exactly where the new one starts touches it and must merge. Checki < nfirst, so that the right side isn't read once the intervals run out. - Inside it, add
intervals[i]toresultand doi++. - Create
startandendasvars set tonewInterval[0]andnewInterval[1]. They describe the growing merged interval. - Part two loop:
while (i < n && intervals[i][0] <= end). Here<=is right, since an interval that starts exactly atendtouches the merged one. - Merge the start:
start = minOf(start, intervals[i][0]). - Merge the end:
end = maxOf(end, intervals[i][1]). The larger value is needed because an interval can lie completely inside the new one. - Advance with
i++. Without it the loop would repeat forever on the same interval. - Add the merged interval with
result.add(intArrayOf(start, end)), after the loop. - Part three loop:
while (i < n), since everything left starts after the merged interval. - Inside it, add
intervals[i]and doi++. - Return
result.toTypedArray(), which converts the list to anArray<IntArray>.
The solution in Kotlin
class Solution {
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
val result = mutableListOf<IntArray>()
val n = intervals.size
var i = 0
while (i < n && intervals[i][1] < newInterval[0]) {
result.add(intervals[i])
i++
}
var start = newInterval[0]
var end = newInterval[1]
while (i < n && intervals[i][0] <= end) {
start = minOf(start, intervals[i][0])
end = maxOf(end, intervals[i][1])
i++
}
result.add(intArrayOf(start, end))
while (i < n) {
result.add(intervals[i])
i++
}
return result.toTypedArray()
}
}
The Kotlin details worth a look:
- Short-circuit
&&. Wheni < nis false, the right side isn't evaluated, sointervals[i]never goes out of bounds. Swapping the two conditions would throw anArrayIndexOutOfBoundsExceptionwhen the intervals run out. whileand a sharedvar. Kotlin has no way to resume aforloop from a given index, so avar iand threewhileloops fit this pattern well. Avalindex couldn't be incremented.- Shared arrays.
result.add(intervals[i])adds the sameIntArrayobject that the input holds, not a copy. The unchanged intervals in the result are the input's own arrays. The merged interval is a fresh array made byintArrayOf. minOfandmaxOfare standard-library functions and need no import.mutableListOfversustoTypedArray(). AMutableListgrows withadd, andtoTypedArray()produces theArray<IntArray>the signature requires.
Complexity
Time: O(n). The index i only moves forward, and every interval is looked at by exactly one of the three loops, with constant work each.
Space: O(n). The result list holds up to n + 1 intervals. Apart from the output, only a few variables are used.
Edge cases and common mistakes
- Empty input.
[]with[5,7]skips parts one and two, adds[5,7]and returns[[5,7]]. - New interval first.
[[3,5]]with[0,1]returns[[0,1],[3,5]]. Part one is empty, and the merged interval comes before the rest. - New interval last.
[[3,5]]with[8,9]returns[[3,5],[8,9]]. Part one takes everything, and the merged interval is added after it. - In a gap.
[[1,2],[5,6]]with[3,4]returns[[1,2],[3,4],[5,6]]. - Inside an existing interval.
[[1,5]]with[2,3]returns[[1,5]]. Taking the smaller start and the larger end is what keeps[1,5]. - Touching on one side.
[[1,4]]with[4,5]returns[[1,5]]. Using<=in part one's condition would put[1,4]into the answer separately and give[[1,4],[4,5]]. - Touching two neighbours.
[[1,2],[3,4]]with[2,3]returns[[1,4]]. - Covering everything.
[[1,2],[3,4]]with[0,10]returns[[0,10]]. - Using
<in part two. That would leave out an interval starting exactly atend, so it would survive as a separate touching interval.
Testing
These inputs give the following results from the reference solution:
[[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]].[[1,5]]with[2,3]gives[[1,5]].[[3,5]]with[0,1]gives[[0,1],[3,5]].[[1,4]]with[4,5]gives[[1,5]].[[1,2],[3,4]]with[2,3]gives[[1,4]].
