Problems › TypeScript › patterns
Answer a stack of range totals
A reporting screen asks for the total of many different day ranges over the same series, and asks a lot of them.
- Each query is a pair taken from the two lists by position: `starts[i]` to `ends[i]`.
- Both ends are inclusive.
- A query whose range falls outside the series, or runs backwards, totals 0.
- Return one total per query, in the order the queries came.
rangeTotals(series: list<int>, starts: list<int>, ends: list<int>) → list<int>
Where you start
function rangeTotals(series: number[], starts: number[], ends: number[]): number[] {
}
Worked examples
| Call | Result |
|---|---|
rangeTotals([1,2,3,4,5], [0,1,0], [2,3,4]) | [6,9,15] |
rangeTotals([1,2,3], [1], [1]) | [2] |
rangeTotals([1,2,3], [2], [1]) | [0] |
rangeTotals([1,2,3], [0], [99]) | [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 TypeScript
function rangeTotals(series: number[], starts: number[], ends: number[]): number[] {
const running: number[] = [0];
for (const value of series) running.push(running[running.length - 1] + value);
const out: number[] = [];
for (let i = 0; i < starts.length; i += 1) {
const from = starts[i];
const to = ends[i];
if (from < 0 || to >= series.length || from > to) out.push(0);
else out.push(running[to + 1] - running[from]);
}
return out;
}