Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in Go: Sort by Start, then One Pass in O(n log n)

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

    GO · INTERVALS

    Merge Intervals in Go, explained

    Problem overview

    The method merge receives intervals, a slice where each interval is a []int holding a start and an end. It merges every group of overlapping intervals and returns the intervals that remain, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5]. The input isn't sorted, and it has at least one interval.

    For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]]: the first two overlap and the other two stand alone. For [[6,8],[1,9],[2,4],[4,7]] the answer is [[1,9]], because [1,9] covers all the rest.

    Approach: sort, then grow the last merged interval

    If the intervals are in random order, any interval might overlap any other, and comparing all pairs takes O(n²). After sorting by start, the intervals that overlap come one after another. Then one pass is enough.

    Keep a slice merged of the results so far. Its last interval is the one that may still grow. For each interval in sorted order:

    • If it starts after the last merged interval ends, it can't overlap anything so far, because every earlier interval ended even sooner. It becomes a new merged interval.
    • Otherwise it overlaps the last one, and the last one's end becomes the larger of the two ends. The larger end matters: an interval can lie completely inside the last one, like [2,3] inside [1,10], and then the end must stay 10.

    Sorting costs O(n log n), and the merging pass is linear. Here is the pass on [[6,8],[1,9],[2,4],[4,7]], after sorting to [[1 9] [2 4] [4 7] [6 8]]:

    after [1 9] -> [[1 9]]
    after [2 4] -> [[1 9]]
    after [4 7] -> [[1 9]]
    after [6 8] -> [[1 9]]

    Why is it enough to compare with only the last merged interval? Every interval in merged before it ends before the last one starts, because a gap was found at the moment the last one was created. The new interval starts at or after the last one's start, so it can't reach back past the last one into an earlier group. The last interval's end is the only boundary that can decide the question.

    Step by step

    1. Sort intervals by start with sort.Slice. Its function func(i, j int) bool returns whether intervals[i][0] < intervals[j][0].
    2. Create merged as an empty [][]int. It will hold the results in order of start.
    3. Loop over the intervals with range, ignoring the index with _. They arrive in order of start.
    4. Name the two ends: start, end := interval[0], interval[1].
    5. Test for a new group. If merged is empty, or the last merged interval's end is less than start, append a new []int{start, end} and store the grown slice back in merged. The test uses <, so touching intervals merge.
    6. Otherwise extend the last interval. In the else branch, set its end to max of its current end and end.
    7. Return merged. Every interval went into a group, in order of start.

    The solution in Go

    type Solution struct {}
    
    func (this Solution) merge(intervals [][]int) [][]int {
        sort.Slice(intervals, func(i, j int) bool {
            return intervals[i][0] < intervals[j][0]
        })
        merged := [][]int{}
        for _, interval := range intervals {
            start, end := interval[0], interval[1]
            if len(merged) == 0 || merged[len(merged)-1][1] < start {
                merged = append(merged, []int{start, end})
            } else {
                merged[len(merged)-1][1] = max(merged[len(merged)-1][1], end)
            }
        }
        return merged
    }
    

    The Go details worth a closer look:

    • append returns a slice. It may allocate a bigger array, so the result must be stored back: merged = append(merged, ...). Calling append without assigning drops the new element.
    • An empty result is still a slice. merged := [][]int{} creates an empty slice with length 0, ready for append. A nil slice would work with append too; this form just makes the intent clear.
    • Evaluating len(merged)-1 is safe because of ||. When merged is empty, the left side is true and Go doesn't evaluate the right side, so there is no read at index -1.
    • The new []int{start, end} is a copy. Extending merged[len(merged)-1][1] changes that new slice, not the caller's inner slices. The caller's outer slice is reordered by the sort, though: sort.Slice sorts in place.
    • The sort package. The lesson already imports sort. In a file of your own, add import "sort". The built-in max needs no import since Go 1.21.

    Complexity

    Time: O(n log n). The sort dominates, and the merging pass makes n constant-time steps.

    Space: O(n) for the result, which in the worst case, with no overlaps, holds a copy of every interval.

    Edge cases and common mistakes

    • Forgetting max. Setting the end to end directly breaks on a contained interval: [[1,10],[2,3]] would become [[1,3]] instead of [[1,10]].
    • Using <= in the new-group test. Touching intervals then stay separate: [[1,4],[4,5]] returns [[1,4],[4,5]] instead of [[1,5]].
    • Skipping the sort. Overlapping intervals might not be next to each other, and the last merged one isn't enough to compare with.
    • Intervals with the same start. [[1,4],[0,4]] sorts to [[0,4],[1,4]] and merges into [[0,4]].
    • Changing the result. Each merged interval is a fresh []int, so assigning to merged[0][1] afterwards doesn't touch the caller's inner slices. For [[1,3],[2,6]], setting the result's end to 99 leaves the input as [[1 3] [2 6]].
    • A single interval or a zero-length one. [[5,5]] returns [[5,5]].
    • Already separate intervals such as [[1,2],[3,4]] come back unchanged.

    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]].
    • [[5,5]] gives [[5,5]].
    • [[1,10],[2,3]] gives [[1,10]].
    • [[1,2],[3,4]] gives [[1,2],[3,4]].
    • [[1,4],[0,4]] gives [[0,4]].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free