Drill

ProblemsJavaScript › patterns

Answer a stack of range totals

mediumpatternsPrefix sumsArraysJavaScript

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>

Solve it in the editor →

Where you start

function rangeTotals(series, starts, ends) {
  
}

Worked examples

CallResult
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 JavaScript
function rangeTotals(series, starts, ends) {
  const running = [0];
  for (const value of series) running.push(running[running.length - 1] + value);
  const out = [];
  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;
}

The same problem in another language

More patterns problems in JavaScript