Drill

ProblemsGo › patterns

Answer a stack of range totals

mediumpatternsPrefix sumsArraysGo

A reporting screen asks for the total of many different day ranges over the same series, and asks a lot of them.

rangeTotals(series: list<int>, starts: list<int>, ends: list<int>) → list<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 rangeTotals(series []int, starts []int, ends []int) []int {
	
}

Worked examples

CallResult
rangeTotals([]int{1, 2, 3, 4, 5}, []int{0, 1, 0}, []int{2, 3, 4})[]int{6, 9, 15}
rangeTotals([]int{1, 2, 3}, []int{1}, []int{1})[]int{2}
rangeTotals([]int{1, 2, 3}, []int{2}, []int{1})[]int{0}
rangeTotals([]int{1, 2, 3}, []int{0}, []int{99})[]int{0}

Hint

Build the running total once, up front. Then any range is one subtraction — the total up to the end, less the total before the start.

Reference solution in Go
func rangeTotals(series []int, starts []int, ends []int) []int {
	running := []int{0}
	for _, value := range series {
	    running = append(running, running[len(running)-1]+value)
	}
	out := []int{}
	for i := 0; i < len(starts); i++ {
	    from, to := starts[i], ends[i]
	    if from < 0 || to >= len(series) || from > to {
	        out = append(out, 0)
	    } else {
	        out = append(out, running[to+1]-running[from])
	    }
	}
	return out
}

The same problem in another language

More patterns problems in Go