Problem overview
The method merge receives intervals, an Array[Array[Int]] where each inner array holds a start and an end. It merges every group of overlapping intervals into one and returns the result as an Array[Array[Int]], sorted by start. Intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5].
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 [[6,8],[1,9],[2,4],[4,7]] the input is unsorted, and [1,9] covers all of the others, so the result is [[1,9]]. The lesson asks for O(n log n) time.
Approach: sort, then extend or start
Comparing every interval with every other one would be O(n²). After sorting by start, intervals that overlap come one after another, so one pass is enough.
Keep a list of merged intervals. For each interval in sorted order, compare it with the last merged one:
- If the interval starts after the last merged interval ends, it overlaps nothing merged so far, and it starts a new merged interval.
- Otherwise it overlaps the last one, so extend that one: its end becomes the larger of its own end and the new interval's end.
The larger end matters because an interval can lie completely inside the last merged one. Merging [2,3] into [1,10] must leave the end at 10.
Sorting is what makes comparing only with the last merged interval safe. In an unsorted list, an interval far from the current one could still overlap it, and a single pass would miss that. In sorted order, every later interval starts at or after the current start. So once an interval starts beyond the last merged end, no later interval can reach back to the intervals before it, and the last merged interval is final.
The sort costs O(n log n) and the pass O(n), so sorting dominates.
Compare this with the brute-force way: repeatedly look for any two overlapping intervals, merge them and start over. That works but can rescan the list many times. The sorted pass touches each interval once.
Step by step
- Sort the intervals by start into a
valnamedsorted:intervals.sortBy(_(0)). - Create
mergedas an emptymutable.ArrayBuffer[Array[Int]]. AnArrayBuffercan grow, which anArraycan't, and we don't know the number of merged intervals in advance. - Loop over each
intervalinsorted. They arrive in order of start. - Name the two ends:
startisinterval(0)andendisinterval(1), each aval. - Start a new interval when needed. If
mergedis empty, or the last merged interval's end,merged(merged.length - 1)(1), is less thanstart, addArray(start, end)with+=. Use<, not<=, because an interval that starts exactly where the last one ends touches it, and touching intervals merge. - Otherwise extend the last interval. In the
elsebranch, set the last merged interval's end tomath.maxof its current end andend. - End with
merged.toArray. Every interval went into a merged one, and they are in order of start.
Here is the state 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]]
The solution in Scala
class Solution {
def merge(intervals: Array[Array[Int]]): Array[Array[Int]] = {
val sorted = intervals.sortBy(_(0))
val merged = mutable.ArrayBuffer[Array[Int]]()
for (interval <- sorted) {
val start = interval(0)
val end = interval(1)
if (merged.isEmpty || merged(merged.length - 1)(1) < start) {
merged += Array(start, end)
} else {
merged(merged.length - 1)(1) = math.max(merged(merged.length - 1)(1), end)
}
}
merged.toArray
}
}
The Scala details worth a closer look:
mutable.ArrayBuffer. The class lives inscala.collection.mutable, and the lesson's code already hasmutablein scope. In a file of your own, addimport scala.collection.mutable. Scala's default collections are immutable, so mutable ones are named explicitly.+=appends. On anArrayBuffer,merged += Array(start, end)adds an element at the end.mergedis aval, but the buffer's contents can change.- Updating a nested element.
merged(merged.length - 1)(1) = ...first reads the last array from the buffer, then assigns to its element 1. That is why the new end replaces the old one inside the same array. ||short-circuits. Whenmerged.isEmptyis true, the right side is never evaluated, so there is no read from an empty buffer.- The input is not changed. The merged intervals are new arrays created with
Array(start, end), andsortByreturns a new array. Aftermerge(Array(Array(1,3), Array(2,6)))the input is still[[1,3],[2,6]]. - Printing arrays. Calling
printlnon anArrayprints a type tag and hash code, such as[[I@..., not the contents. UsemkStringto print them.
Complexity
Time: O(n log n), where n is the number of intervals. Sorting is O(n log n), and the loop does a constant amount of work per interval.
Space: O(n). The sorted array and the buffer each hold up to n entries.
Edge cases and common mistakes
- Touching intervals.
[[1,4],[4,5]]gives[[1,5]]. With<=in the test, they would stay as two intervals,[[1,4],[4,5]]. - Unsorted input.
[[1,4],[0,4]]gives[[0,4]]. Without the sort, the second interval's smaller start would never be used. - Containment.
[[1,10],[2,3]]gives[[1,10]]. If the code assignedendinstead of taking the larger value, the result would be[[1,3]]. - A single interval.
[[5,5]]returns[[5,5]]. - Intervals that don't overlap.
[[1,2],[3,4]]stays as it is. - A bridging interval.
[[2,3],[1,10],[11,12]]gives[[1,10],[11,12]]: the middle one swallows[2,3]and ends before[11,12]starts.
Testing
[[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]].[[1,10],[2,3]]gives[[1,10]].[[1,4],[0,0]]gives[[0,0],[1,4]].[[5,5]]gives[[5,5]].
