← Pointer Manipulation

Micro-Drill #270 — Prefix sum build and query

Pointer Manipulation Target: 10s

Prefix sum gives O(1) range queries after O(n) build. p[r+1] - p[l] = sum(a[l..r]). Off-by-one: p has length n+1.

p = [0] * (len(a) + 1)
for i in range(len(a)):
    p[i+1] = p[i] + a[i]
# range sum [l, r] inclusive:
total = p[r+1] - p[l]

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #269 Micro #271 →