Algorithms · Level 1 Arrays

Prefix Sums

Answer thousands of "how much did we sell between day a and day b?" questions with one list of running totals and one subtraction each.

  • prefix[i] = total of the first i items
  • range total = prefix[end + 1] - prefix[start]
  • O(n + q) instead of O(n × q)

A prefix list stores running totals: prefix[i] is the sum of the first i items. Any range total is then one subtraction, so q questions cost O(n + q). Trap: make it one longer than the data, starting with 0.

prefix = [0]
for x in [4, 2, 7]:
    prefix.append(prefix[-1] + x)
prefix                  # [0, 4, 6, 13]
prefix[3] - prefix[1]   # 9 = 2 + 7

Write range_totals(sales, queries): for each (start, end) pair of days (both included, counted from 0), the total sold. Example: range_totals([4, 2, 7, 1], [(1, 2), (0, 3)]) → [9, 14].

solution.py
Test Suites Pending
Output