Problem overview
The function merge receives intervals, an Array<IntArray> where each element is a pair [start, end]. It merges every group of overlapping intervals and returns the intervals that remain as an Array<IntArray>, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, such as [1,4] and [4,5], merge into [1,5]. There can be up to 100,000 intervals, and the statement asks for O(n log n) time.
For [[1,3],[2,6],[8,10],[15,18]] the result is [[1,6],[8,10],[15,18]]: the first two overlap and the others stand alone. For the unsorted [[6,8],[1,9],[2,4],[4,7]] the result is [[1,9]], because [1,9] covers all the others.
Approach: sort by start, then extend the last interval
Comparing every pair of intervals would be O(n²). After sorting by start, intervals that belong together are adjacent, and one pass is enough. Keep a list of merged intervals. For each interval in sorted order, look at the last merged interval:
- If the last merged interval ends before this one starts, there is a gap, and nothing merged so far can overlap it. Add the interval as a new merged one.
- Otherwise they overlap, and the last merged interval grows to cover both. Its end becomes the larger of the two ends. The larger one is needed because an interval can sit completely inside the last one:
[2,3]inside[1,10]must leave the end at 10.
Only the last merged interval needs checking. Every interval that follows starts at or after the start of the current one, so it can't reach back to an earlier merged interval that ended before a gap.
The state of the list after each interval of the first example:
after [1,3]: [[1, 3]]
after [2,6]: [[1, 6]]
after [8,10]: [[1, 6], [8, 10]]
after [15,18]: [[1, 6], [8, 10], [15, 18]]
Step by step
- Sort by start with
intervals.sortBy { it[0] }. - Create
mergedas avalholdingmutableListOf<IntArray>(). Its size isn't known in advance, so it must be able to grow. - Loop over
intervalswithfor ((start, end) in intervals), which unpacks each pair into two names. - Start a new interval when needed. If
merged.isEmpty()ormerged.last()[1] < start, addintArrayOf(start, end)tomerged. Use<, not<=, because touching intervals merge. - Otherwise extend the last one. In the
elsebranch, setmerged.last()[1]tomaxOf(merged.last()[1], end). - Return
merged.toTypedArray(), which converts the list to theArray<IntArray>the function must return.
The solution in Kotlin
class Solution {
fun merge(intervals: Array<IntArray>): Array<IntArray> {
intervals.sortBy { it[0] }
val merged = mutableListOf<IntArray>()
for ((start, end) in intervals) {
if (merged.isEmpty() || merged.last()[1] < start) {
merged.add(intArrayOf(start, end))
} else {
merged.last()[1] = maxOf(merged.last()[1], end)
}
}
return merged.toTypedArray()
}
}
The Kotlin details worth a look:
sortBysorts in place. It reordersintervalsitself and returns nothing, and the lambda gives the key to sort by. The sort is stable, so intervals with the same start keep their order.- Destructuring.
for ((start, end) in intervals)works on anIntArraybecause arrays providecomponent1()andcomponent2()functions for their first elements. Herestartis element 0 andendis element 1. The names are plainIntvalues, copies of the numbers. - Short-circuit
||. Whenmergedis empty, the left side istrueandmerged.last()is never evaluated. Callinglast()on an empty list would throw aNoSuchElementException, so the order of the two conditions matters. valwith a mutable list.val mergedmeans the variable can't be reassigned, but the list it refers to can still grow withadd.- Changing an element of the last interval.
merged.last()[1] = ...writes into theIntArraythatlast()returns. That array was created byintArrayOf(start, end), so it is a copy, and the caller's input arrays aren't modified (althoughsortBydoes reorder the outer array). toTypedArray()turns aList<IntArray>into anArray<IntArray>, the type in the function signature.
Complexity
Let n be the number of intervals.
Time: O(n log n). Sorting dominates, and the pass after it is O(n), with each interval handled in constant time.
Space: O(n). In the worst case, when no intervals overlap, merged holds a new array for every interval, and the returned array is another n references.
Edge cases and common mistakes
- A single interval.
[[5,5]]returns[[5,5]]. A zero-length interval is allowed by the constraints. - An interval inside another.
[[1,10],[2,3]]returns[[1,10]]. Setting the end toendinstead of the larger value would give[[1,3]]. - Touching intervals.
[[1,4],[4,5]]returns[[1,5]]. With<=in the first condition the result would stay[[1,4],[4,5]]. - Gaps.
[[1,2],[3,4]]returns both intervals unchanged, because 2 is less than 3. - Duplicates.
[[2,3],[2,3],[2,3]]returns[[2,3]]. - Same start.
[[0,0],[0,1]]returns[[0,1]]. - Skipping the sort. On unsorted input such as
[[6,8],[1,9],[2,4],[4,7]], comparing only with the last merged interval would miss overlaps. - Printing the result. Printing an
Array<IntArray>directly shows object references such as[[I@.... UsecontentDeepToString()to see the numbers.
Testing
These inputs give the following results from the reference solution:
[[1,3],[2,6],[8,10],[15,18]]gives[[1,6],[8,10],[15,18]].[[1,4],[4,5]]gives[[1,5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1,9]].[[5,5]]gives[[5,5]].[[1,10],[2,3]]gives[[1,10]].[[1,2],[3,4]]gives[[1,2],[3,4]].[[2,3],[2,3],[2,3]]gives[[2,3]].
