Problem Solving with Go course

Sorting and SearchingMerging Intervals

Problem Solving with Go

Display

Theme

Sorting and Searching · Test exercise

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 max when extending. A range can sit entirely inside the previous one (1-10 then 2-3), and taking its Hi would shrink the result.
  • Decide whether ranges that only touch merge. With whole-number ranges where both ends count, 3-5 and 6-8 leave no gap, so they join into 3-8: the test becomes r.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.

  1. Complete mergeRanges(ranges []Range) []Range: the ranges sorted by Lo, with ranges that overlap or touch joined. Don't change the argument.
  2. Complete closedLength(ranges []Range) int: how many kilometres are inside at least one range.
  3. Complete isClosed(merged []Range, km int) bool: whether km is inside one of the ranges in merged, the result of mergeRanges. Use binary search.
main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"slices"
	"strconv"
	"strings"
)

// Range is a stretch of road from kilometre Lo to kilometre Hi, both included.
type Range struct {
	Lo, Hi int
}

// mergeRanges returns the ranges sorted by Lo, with ranges that overlap or touch
// (such as 3-5 and 6-8) joined into one. The argument is not changed.
func mergeRanges(ranges []Range) []Range {
	// TODO: sort a copy by Lo, then grow the last range or start a new one
	return slices.Clone(ranges)
}

// closedLength returns how many kilometres are inside at least one range.
func closedLength(ranges []Range) int {
	// TODO
	return 0
}

// isClosed reports whether km is inside one of merged, the result of mergeRanges.
func isClosed(merged []Range, km int) bool {
	// TODO: binary search for the first range that ends at km or later
	return false
}

func main() {
	var works []Range
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		lo, hi, ok := strings.Cut(strings.TrimSpace(scanner.Text()), "-")
		a, err1 := strconv.Atoi(lo)
		b, err2 := strconv.Atoi(hi)
		if !ok || err1 != nil || err2 != nil {
			continue
		}
		works = append(works, Range{a, b})
	}
	merged := mergeRanges(works)
	fmt.Println("closed stretches:", merged)
	fmt.Println("kilometres closed:", closedLength(works))
	for _, km := range []int{9, 21, 35} {
		fmt.Printf("is kilometre %d closed? %v\n", km, isClosed(merged, km))
	}
}
Go runtime not loaded yet

7 lines · 38 B of the 1 MB limit. Submit always uses the lesson's own input.