Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in Kotlin: O(n log n) by Sorting and 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 6
    Ctrl + Enter to check

    KOTLIN · INTERVALS

    Merge Intervals in Kotlin, explained

    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

    1. Sort by start with intervals.sortBy { it[0] }.
    2. Create merged as a val holding mutableListOf<IntArray>(). Its size isn't known in advance, so it must be able to grow.
    3. Loop over intervals with for ((start, end) in intervals), which unpacks each pair into two names.
    4. Start a new interval when needed. If merged.isEmpty() or merged.last()[1] < start, add intArrayOf(start, end) to merged. Use <, not <=, because touching intervals merge.
    5. Otherwise extend the last one. In the else branch, set merged.last()[1] to maxOf(merged.last()[1], end).
    6. Return merged.toTypedArray(), which converts the list to the Array<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:

    • sortBy sorts in place. It reorders intervals itself 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 an IntArray because arrays provide component1() and component2() functions for their first elements. Here start is element 0 and end is element 1. The names are plain Int values, copies of the numbers.
    • Short-circuit ||. When merged is empty, the left side is true and merged.last() is never evaluated. Calling last() on an empty list would throw a NoSuchElementException, so the order of the two conditions matters.
    • val with a mutable list. val merged means the variable can't be reassigned, but the list it refers to can still grow with add.
    • Changing an element of the last interval. merged.last()[1] = ... writes into the IntArray that last() returns. That array was created by intArrayOf(start, end), so it is a copy, and the caller's input arrays aren't modified (although sortBy does reorder the outer array).
    • toTypedArray() turns a List<IntArray> into an Array<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 to end instead 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@.... Use contentDeepToString() 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]].
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free