Drill

ProblemsGo › patterns

How many stretches add up to the figure

hardpatternsPrefix sumsHash mapsArraysGo

An investigator looks through a list of movements for every unbroken stretch that comes to a particular amount.

stretchesTotalling(movements: list<int>, target: int) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func stretchesTotalling(movements []int, target int) int {
	
}

Worked examples

CallResult
stretchesTotalling([]int{1, 1, 1}, 2)2
stretchesTotalling([]int{1, 2, 3}, 3)2
stretchesTotalling([]int{1, -1, 0}, 0)3
stretchesTotalling([]int{}, 0)0

Hint

If the running total at two points differs by the target, the stretch between them is a hit. Keep a count of every running total you have seen and look up total minus target.

Reference solution in Go
func stretchesTotalling(movements []int, target int) int {
	seen := map[int]int{0: 1}
	running, hits := 0, 0
	for _, movement := range movements {
	    running += movement
	    hits += seen[running-target]
	    seen[running]++
	}
	return hits
}

The same problem in another language

More patterns problems in Go