Part 17 / Topic 4 of 20
Prefix sums and difference arrays
A prefix-sum array stores running totals: prefix[i] = sum of the first i values, with prefix[0] = 0. Build it once in O(n), and the total of ANY range l..r becomes one subtraction โ prefix[r + 1] - prefix[l] โ instead of an O(n) re-sum per question. A difference array is the same trick backwards: record only the changes at range edges, then one O(n) pass turns them into final values, so a thousand "add x to every day in this range" updates cost O(1) each.
Think of the odometer in a car: to know the kilometres driven between two trips you subtract two readings โ nobody re-adds every single drive in between.
| Question | Naive | With prefix/difference |
|---|---|---|
| total of range l..r, asked many times | O(n) per question | O(1) per question after an O(n) build |
| apply many "add x to range" updates | O(range length) each | O(1) each, one O(n) finish |
def build_prefix(values):
prefix = [0]
for v in values:
prefix.append(prefix[-1] + v)
return prefix
daily_sales = [1200, 900, 1500, 2100, 1800, 700, 2600]
prefix = build_prefix(daily_sales)
print(prefix) # [0, 1200, 2100, 3600, 5700, 7500, 8200, 10800]
print(prefix[5] - prefix[2]) # 5400: days 2..4, one subtraction
The difference array, applying three bulk seat bookings in O(1) each:
days = 7
diff = [0] * (days + 1)
for first, last, seats in [(0, 2, 10), (1, 4, 5), (3, 6, 8)]:
diff[first] += seats # the change starts here...
diff[last + 1] -= seats # ...and stops after here
booked, running = [], 0
for day in range(days):
running += diff[day]
booked.append(running)
print(booked) # [10, 15, 15, 13, 13, 8, 8]
Real-world example: a hotel's "seats booked per day" chart over a season is exactly the difference-array pattern โ each booking touches two numbers, no matter how long it is, and one pass at the end draws the chart.
โ ๏ธ Off-by-one is the whole game here: with
prefix[0] = 0, the inclusive rangel..risprefix[r + 1] - prefix[l]. Write that identity down once and test it on a 3-item list before trusting it.
Practice: range-sum questions answered from one prefix build; find a pivot/balance index where left total equals right total; bulk range updates with a difference array.
Practice on LeetCode - start here: Running Sum of 1d Array ยท Find Pivot Index ยท Range Sum Query - Immutable
Show the full practice list (9 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Subarray Sum Equals K | Medium |
| Contiguous Array | Medium |
| Product of Array Except Self | Medium |
| Range Sum Query 2D - Immutable | Medium |
| Car Pooling | Medium |
| Corporate Flight Bookings | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Continuous Subarray Sum | Medium |
| Matrix Block Sum | Medium |
| Subarray Sums Divisible by K | Medium |
Full program: examples/04_prefix_sums.py.
Exercise 4: Prefix sums โ step counts by date range
Scenario: A fitness app stores one week of daily step counts and must answer "how many steps between day l and day r?" instantly, many times.
What to do: Write build_prefix(values) returning prefix with prefix[0] = 0 and prefix[i] = total of the first i days, and range_total(prefix, left, right) returning the inclusive range total as prefix[right + 1] - prefix[left]. Answer the three queries below.
Starting data:
DAILY_STEPS = [4000, 7500, 3000, 10000, 6500, 8000, 5000]
QUERIES = [(0, 2), (3, 5), (0, 6)]
Sample output:
Days 0..2: 14500 steps
Days 3..5: 24500 steps
Days 0..6: 44000 steps
Show the solution to Exercise 4
"""Exercise 4: Prefix sums - range totals without re-summing.
One O(n) build of prefix[], then every range question is two lookups:
prefix[right + 1] - prefix[left].
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
DAILY_STEPS = [4000, 7500, 3000, 10000, 6500, 8000, 5000]
QUERIES = [(0, 2), (3, 5), (0, 6)]
def build_prefix(values: list[int]) -> list[int]:
prefix = [0]
for v in values:
prefix.append(prefix[-1] + v)
return prefix
def range_total(prefix: list[int], left: int, right: int) -> int:
return prefix[right + 1] - prefix[left]
def main() -> None:
prefix = build_prefix(DAILY_STEPS)
for left, right in QUERIES:
print(f"Days {left}..{right}: {range_total(prefix, left, right)} steps")
if __name__ == "__main__":
main()