DevPath

← All problems

Merge Intervals

Medium sorting · arrays

Description

Merge all overlapping intervals and return the non-overlapping result in ascending order.

Constraints

1 <= intervals <= 10000

Examples

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

Hints (1)
  • Sort by start; merge while the next start is within the current end.

Solutions

Sort by start then sweep. (requires "sort") · Time O(n log n) · Space O(n)

func mergeIntervals(intervals [][]int) [][]int {
    sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
    out := [][]int{}
    for _, iv := range intervals {
        if len(out) > 0 && iv[0] <= out[len(out)-1][1] {
            if iv[1] > out[len(out)-1][1] {
                out[len(out)-1][1] = iv[1]
            }
        } else {
            out = append(out, []int{iv[0], iv[1]})
        }
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account