Problem Solving with Go course

ComplexityPrefix Sums: Compute Once, Answer Many Times

Problem Solving with Go

Display

Theme

Complexity · Test exercise

Prefix Sums: Compute Once, Answer Many Times

Picture a year of daily step counts, then a thousand questions like "how many steps from day 40 to day 200?". The direct way adds up every range again:

total := 0
for i := from; i <= to; i++ {
	total += steps[i]
}

One question can take n steps, so q questions take up to n × q. With 100,000 days and 100,000 questions, that's 10 billion additions.

Keep a running total

A prefix sum stores the total of every value before each position:

xs:      4   8   3   7
p:   0   4  12  15  22

p[i] is the sum of xs[0:i], so p has one more value than xs and always starts with 0. Building it takes one pass:

p := make([]int, len(xs)+1)
for i, x := range xs {
	p[i+1] = p[i] + x
}

Every range becomes one subtraction

The sum of xs[from] through xs[to] (both included) is everything before to + 1, minus everything before from:

sum := p[to+1] - p[from]

One O(n) pass to build it, then every question is O(1). That's the heart of choosing a data structure: do some work once up front, so the questions that repeat become cheap.

Watch out for off-by-one errors: puzzles often number days from 1, while Go indexes from 0. Convert in one place only, when reading the input, as main does in this lesson.

Task

  1. Complete prefixSums(xs []int) []int: a slice of length len(xs)+1 with p[i] = the sum of xs[0:i]. For an empty slice, the result is [0].
  2. Complete rangeSum(p []int, from, to int) int: the sum of xs[from] through xs[to], both included, with one subtraction from p.

main already reads the step log and the range questions from the input.

main.go
package main

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

// prefixSums returns p with len(xs)+1 values: p[i] is the sum of xs[0:i].
func prefixSums(xs []int) []int {
	// TODO
	return nil
}

// rangeSum is the sum of xs[from] through xs[to], both included, from its prefix sums.
func rangeSum(p []int, from, to int) int {
	// TODO: one subtraction, no loop
	return 0
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var prefix []int
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) == 0 {
			continue
		}
		switch fields[0] {
		case "steps":
			var steps []int
			for _, f := range fields[1:] {
				n, err := strconv.Atoi(f)
				if err != nil {
					fmt.Println("bad number:", f)
					return
				}
				steps = append(steps, n)
			}
			prefix = prefixSums(steps)
		case "days":
			var from, to int
			if len(fields) != 2 || prefix == nil {
				fmt.Println("want \"days <from>-<to>\" after the steps line")
				return
			}
			if _, err := fmt.Sscanf(fields[1], "%d-%d", &from, &to); err != nil {
				fmt.Println("bad range:", fields[1])
				return
			}
			// Days are numbered from 1 in the input, indexes from 0 in Go.
			fmt.Printf("days %d-%d: %d steps\n", from, to, rangeSum(prefix, from-1, to-1))
		}
	}
}
Go runtime not loaded yet

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