Drill

ProblemsPython › patterns

Answer a stack of range totals

mediumpatternsPrefix sumsArraysPython

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

range_totals(series: list<int>, starts: list<int>, ends: list<int>) → list<int>

Solve it in the editor →

Where you start

def range_totals(series: list[int], starts: list[int], ends: list[int]) -> list[int]:
    

Worked examples

CallResult
range_totals([1, 2, 3, 4, 5], [0, 1, 0], [2, 3, 4])[6, 9, 15]
range_totals([1, 2, 3], [1], [1])[2]
range_totals([1, 2, 3], [2], [1])[0]
range_totals([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 Python
def range_totals(series: list[int], starts: list[int], ends: list[int]) -> list[int]:
    running = [0]
    for value in series:
        running.append(running[-1] + value)
    out = []
    for i in range(len(starts)):
        from_i, to_i = starts[i], ends[i]
        if from_i < 0 or to_i >= len(series) or from_i > to_i:
            out.append(0)
        else:
            out.append(running[to_i + 1] - running[from_i])
    return out

The same problem in another language

More patterns problems in Python