Merging Intervals
Puzzles love ranges: opening hours, seat numbers, valid ID ranges, stretches of road. As soon as ranges overlap, questions like "how much is covered in total?" get awkward, because the shared part must not be counted twice. The fix is to merge them first.
Sort, then sweep
Sort the ranges by where they start. Then go through them once, keeping a list of merged ranges. Each new range either overlaps the last merged range, so it extends it, or starts after it, so it begins a new one:
slices.SortFunc(rs, func(a, b Range) int { return cmp.Compare(a.Lo, b.Lo) })
var out []Range
for _, r := range rs {
if n := len(out); n > 0 && r.Lo <= out[n-1].Hi {
out[n-1].Hi = max(out[n-1].Hi, r.Hi)
} else {
out = append(out, r)
}
}
Two details catch people out:
- Use
maxwhen extending. A range can sit entirely inside the previous one (1-10then2-3), and taking itsHiwould shrink the result. - Decide whether ranges that only touch merge. With whole-number ranges where both ends count,
3-5and6-8leave no gap, so they join into3-8: the test becomesr.Lo <= last.Hi+1.
Sorting costs O(n log n) and the sweep O(n). After that the merged ranges are sorted and don't overlap, and adding up their lengths gives the total coverage: Hi - Lo + 1 for each.
Questions on merged ranges
Because merged ranges are sorted and separate, "is this value covered?" is a binary search: find the first range that ends at the value or later, then check that it starts at the value or earlier.
Task
Road works close stretches of a road. This lesson's input has one closed stretch per line, as from-to in whole kilometres, both included.
- Complete
mergeRanges(ranges []Range) []Range: the ranges sorted byLo, with ranges that overlap or touch joined. Don't change the argument. - Complete
closedLength(ranges []Range) int: how many kilometres are inside at least one range. - Complete
isClosed(merged []Range, km int) bool: whetherkmis inside one of the ranges inmerged, the result ofmergeRanges. Use binary search.