Merge Overlapping Intervals In Place
Sort intervals by start, then extend the last merged span while the next one overlaps, collapsing an unsorted timeline into disjoint ranges.
Code
package main
import (
"cmp"
"fmt"
"slices"
)
// Interval 表示闭区间 [Start, End]
type Interval struct{ Start, End int }
// merge sorts intervals in place by start, then merges the overlapping ones
func merge(intervals []Interval) []Interval {
slices.SortFunc(intervals, func(a, b Interval) int {
return cmp.Compare(a.Start, b.Start)
})
merged := []Interval{}
for _, iv := range intervals {
if n := len(merged); n > 0 && iv.Start <= merged[n-1].End {
if iv.End > merged[n-1].End {
merged[n-1].End = iv.End // 重叠:延长最后一个区间
}
continue
}
merged = append(merged, iv)
}
return merged
}
func main() {
spans := []Interval{{8, 10}, {1, 3}, {2, 6}, {15, 18}}
for _, iv := range merge(spans) {
fmt.Printf("[%d, %d]\n", iv.Start, iv.End)
}
}Collapsing overlapping intervals
Structurally, expect the functions merge and main and nothing else.
Iteration happens inside for _, iv := range intervals — everything outside it runs once.
Applying it
Entry signature: func merge(intervals []Interval) []Interval
The entry point wires merge together — run it once and the whole demo flows.
Statements that matter
for _, iv := range merge(spans) {
fmt.Printf("[%d, %d]\n", iv.Start, iv.End)
}
for _, iv := range intervals {
if n := len(merged); n > 0 && iv.Start <= merged[n-1].End {
if iv.End > merged[n-1].End {
merged[n-1].End = iv.End // 重叠:延长最后一个区间
}
continue
}
merged = append(merged, iv)
}
return cmp.Compare(a.Start, b.Start)
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.
FAQ
- How do you run Merge Overlapping Intervals In Place?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.