Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in Scala: Sort by Start, then One Pass

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    SCALA · INTERVALS

    Merge Intervals in Scala, explained

    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

    1. Sort the intervals by start into a val named sorted: intervals.sortBy(_(0)).
    2. Create merged as an empty mutable.ArrayBuffer[Array[Int]]. An ArrayBuffer can grow, which an Array can't, and we don't know the number of merged intervals in advance.
    3. Loop over each interval in sorted. They arrive in order of start.
    4. Name the two ends: start is interval(0) and end is interval(1), each a val.
    5. Start a new interval when needed. If merged is empty, or the last merged interval's end, merged(merged.length - 1)(1), is less than start, add Array(start, end) with +=. Use <, not <=, because an interval that starts exactly where the last one ends touches it, and touching intervals merge.
    6. Otherwise extend the last interval. In the else branch, set the last merged interval's end to math.max of its current end and end.
    7. 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 in scala.collection.mutable, and the lesson's code already has mutable in scope. In a file of your own, add import scala.collection.mutable. Scala's default collections are immutable, so mutable ones are named explicitly.
    • += appends. On an ArrayBuffer, merged += Array(start, end) adds an element at the end. merged is a val, 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. When merged.isEmpty is 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), and sortBy returns a new array. After merge(Array(Array(1,3), Array(2,6))) the input is still [[1,3],[2,6]].
    • Printing arrays. Calling println on an Array prints a type tag and hash code, such as [[I@..., not the contents. Use mkString to 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 assigned end instead 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]].
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free