Problem Solving with Go course

Sorting and SearchingBinary Search

Problem Solving with Go

Display

Theme

Sorting and Searching · Test exercise

Binary Search

Looking for a value in an unsorted list means checking every element: O(n). In a sorted list you can do much better. Look at the middle: if the value there is too small, the answer is in the right half; otherwise it's in the left half. Each look throws away half of what's left, so a million elements need only about 20 looks: O(log n).

sort.Search

Writing binary search by hand is famous for off-by-one bugs. Go's sort.Search does it for you, and it's more general than "find this value":

i := sort.Search(n, func(i int) bool { return xs[i] >= 50 })

sort.Search(n, f) returns the smallest i in [0, n) for which f(i) is true, or n if there is none. The one rule: f must be false, false, ..., then true, true, ... and never switch back. For a sorted slice, xs[i] >= target has exactly that shape.

So the line above finds the first value that is at least 50. To check whether 50 itself is there, test i < len(xs) && xs[i] == 50. For the common case, slices.BinarySearch(xs, 50) returns both the position and whether it was found.

Counting a range

How many values lie between lo and hi? Find where the values >= lo start, and where the values >= hi+1 start. Everything in between is in the range:

count := firstAtLeast(xs, hi+1) - firstAtLeast(xs, lo)

Two searches, O(log n), no matter how many values are in the range.

Searching for the answer

sort.Search doesn't need a slice at all, only a yes/no question that switches from no to yes once. That makes it useful when the answer itself is a number you could search for: "what's the smallest size that's big enough?" If you can check one candidate quickly, you can binary search over all candidates:

side := sort.Search(2_000_000_000, func(s int) bool { return s*s >= tiles })

Checking two billion sizes one by one would take ages; binary search needs about 31 checks.

Task

This lesson's input is a list of seconds at which a doorbell rang.

  1. Complete firstAtLeast(sorted []int, target int) int: the index of the first value >= target, or len(sorted) when there is none.
  2. Complete countBetween(sorted []int, lo, hi int) int: how many values are between lo and hi, both included. When hi < lo, that's 0.
  3. Complete smallestSide(tiles int) int: the smallest whole number s with s*s >= tiles. The tests go up to tiles = 10^18, so search for the answer.
main.go
package main

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

// firstAtLeast returns the index of the first value in sorted that is >= target,
// or len(sorted) when there is none.
func firstAtLeast(sorted []int, target int) int {
	// TODO: sort.Search(n, f) returns the first i for which f(i) is true
	return 0
}

// countBetween returns how many values in sorted are between lo and hi, both included.
func countBetween(sorted []int, lo, hi int) int {
	// TODO: two calls to firstAtLeast
	return 0
}

// smallestSide returns the smallest whole number s with s*s >= tiles: the side of the
// smallest square that holds that many square tiles. tiles is at most 10^18.
func smallestSide(tiles int) int {
	// TODO: search the answer itself; s is never more than 2,000,000,000
	return 0
}

func main() {
	var rings []int
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		n, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
		if err != nil {
			continue
		}
		rings = append(rings, n)
	}
	sort.Ints(rings)
	fmt.Println("doorbell rings in the first minute:", countBetween(rings, 0, 59))
	fmt.Println("between 2 and 4 minutes:", countBetween(rings, 120, 240))
	fmt.Println("first ring from second 100 on is number", firstAtLeast(rings, 100)+1)
	fmt.Println("smallest square for", len(rings), "tiles has a side of", smallestSide(len(rings)))
}
Go runtime not loaded yet

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