Skip to content
Visual explainer 3h to learn 5 steps

Prefix sums & in-place array techniques

Answer range-sum queries in O(1) and rearrange arrays in place without extra memory.

By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.

Topic 9 of 54

In short

A prefix sum array stores the running total up to each index, so any range sum becomes one subtraction. Building it costs O(n) once, after which each query is O(1). The same idea extends to 2D grids and pairs well with in-place techniques like reversal and partitioning.

Explained simply

Imagine a shop that writes down its total sales so far at the end of each day. To find sales from Tuesday to Friday, you do not add four days. You take Friday's running total and subtract Monday's. That running total is a prefix sum.

In code, you make a new list where each spot holds the sum of everything before it. Building it takes one pass. After that, the sum of any section is just one subtraction, no matter how long the section is.

This matters when you have many questions about the same data. Adding up a range each time costs O(n) per question. With prefix sums, you pay O(n) once and then every question is O(1).

A related family of tricks rearranges an array without making a copy, called in-place. You can reverse, rotate, or split an array into two groups by swapping items, using only a couple of index variables.

Press Play on a diagram to walk through it one step at a time.

FlowRange sum with prefix sums
  1. Step 1
    Input

    a = [3, 1, 4, 1, 5]

  2. Step 2
    Build prefix

    p = [0, 3, 4, 8, 9, 14]

  3. Step 3
    Query sum(a[1..3])

    p[4] - p[1]

  4. Step 4
    Answer

    9 - 3 = 6 in O(1)

FlowCounting subarrays with sum 3 in [1, 2, 1, 2]
  1. 1
    Start

    total=0, seen {0:1}, count=0

  2. 2
    Add 1

    total=1, need -2: none; seen {0:1, 1:1}

  3. 3
    Add 2

    total=3, need 0: +1; count=1

  4. 4
    Add 1

    total=4, need 1: +1; count=2

  5. 5
    Add 2

    total=6, need 3: +1; count=3

  6. 6
    Answer

    [1,2], [2,1], [1,2] = 3 subarrays

In depth

Why the leading zero helps

Define p[0] = 0 and p[k] = a[0] + ... + a[k-1]. So p has one more slot than a. Then the sum of a[i] through a[j] is p[j+1] - p[i].

Without the leading zero, a range that starts at index 0 needs a special case. With it, every query uses the same formula. Think of p[k] as "the total before index k", and the off-by-one errors disappear.

  • p has length n + 1
  • sum(a[i..j]) = p[j+1] - p[i]
  • Build: p[k+1] = p[k] + a[k]

Prefix sums plus a hash map

To count subarrays that sum to k, notice that the sum of a[i..j] equals k exactly when p[j+1] - p[i] = k, which means p[i] = p[j+1] - k.

So walk the array once, keeping the running total, and a dict counting how often each earlier prefix total appeared. At each step, add the count of (total - k) to the answer. This handles negative numbers too, which sliding windows cannot. The same idea finds the longest subarray with sum k by storing the first index of each total.

2D prefix sums for rectangles

For a grid, let P[r][c] be the sum of everything above and to the left of (r, c), with an extra zero row and column. Build it with P[r+1][c+1] = g[r][c] + P[r][c+1] + P[r+1][c] - P[r][c]. The subtraction removes the corner area counted twice.

Then any rectangle from (r1, c1) to (r2, c2) is P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]. Four lookups, O(1), no matter how large the rectangle.

In-place moves: reverse, rotate, partition

Reverse: swap the ends and walk inward. Rotate right by k: reverse the whole array, then reverse the first k items, then reverse the rest. For [1,2,3,4,5] and k = 2: [5,4,3,2,1], then [4,5,3,2,1], then [4,5,1,2,3].

Partition: to put all items matching a rule first, keep a write index w. For each item that matches, swap it into position w and increase w. One pass, O(1) space, and it is the heart of quicksort.

  • Rotate by k: reverse all, reverse [0, k), reverse [k, n)
  • Always do k %= n first
  • Partition with a write pointer
FlowRotate [1,2,3,4,5] right by 2
  1. Step 1
    Start

    [1, 2, 3, 4, 5], k = 2

  2. Step 2
    Reverse all

    [5, 4, 3, 2, 1]

  3. Step 3
    Reverse first k

    [4, 5, 3, 2, 1]

  4. Step 4
    Reverse the rest

    [4, 5, 1, 2, 3]

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Build 1D prefix sum arrays~35m
  2. 2
    Answer range queries in constant time~35m
  3. 3
    Use 2D prefix sums for submatrices~35m
  4. 4
    Reverse and rotate arrays in place~35m
  5. 5
    Partition an array in one pass~35m

Key points

  • Build: O(n) time and space; query: O(1).
  • Using a leading zero, sum(a[i..j]) = p[j+1] - p[i].
  • 2D: sum of a rectangle uses four lookups with inclusion-exclusion.
  • Rotate an array in place in O(n) with three reversals.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from itertools import accumulate

a = [3, 1, 4, 1, 5]
p = [0, *accumulate(a)]           # O(n)

def range_sum(i, j):              # inclusive, O(1)
    return p[j + 1] - p[i]

def rotate_right(xs, k):          # in place, O(n)
    k %= len(xs)
    xs.reverse()
    xs[:k] = reversed(xs[:k]); xs[k:] = reversed(xs[k:])

print(range_sum(1, 3))  # 6

Range queries traced

a = [2, 4, 1, 3, 5]. Build p = [0, 2, 6, 7, 10, 15]. Query sum of indexes 1 to 3 (4 + 1 + 3 = 8): p[4] - p[1] = 10 - 2 = 8. Query 0 to 4: p[5] - p[0] = 15. Query 2 to 2: p[3] - p[2] = 1. Three queries, each one subtraction.

python
a = [2, 4, 1, 3, 5]
p = [0]
for x in a:
    p.append(p[-1] + x)
print(p)  # [0, 2, 6, 7, 10, 15]

for i, j in [(1, 3), (0, 4), (2, 2)]:
    print(i, j, p[j + 1] - p[i])
# 1 3 8 / 0 4 15 / 2 2 1

Rectangle sums in a grid

Grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. We want the sum of the bottom-right 2 x 2 block: 5 + 6 + 8 + 9 = 28. Build P with an extra zero row and column. The formula takes the big rectangle up to (2, 2), removes the strip above and the strip to the left, and adds back the corner removed twice: 45 - 6 - 12 + 1 = 28.

python
g = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
R, C = len(g), len(g[0])
P = [[0] * (C + 1) for _ in range(R + 1)]
for r in range(R):
    for c in range(C):
        P[r+1][c+1] = g[r][c] + P[r][c+1] + P[r+1][c] - P[r][c]

def rect(r1, c1, r2, c2):
    return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]

print(rect(1, 1, 2, 2))  # 28

Quick reference

  • p[0] = 0, p[k+1] = p[k] + a[k]
  • sum(a[i..j]) = p[j+1] - p[i]
  • Subarrays with sum k: count earlier prefix totals equal to total - k
  • 2D rectangle: big - top - left + corner
  • Rotate right by k: reverse all, reverse first k, reverse rest
  • Frequent updates? Use a Fenwick tree, not prefix sums
  • itertools.accumulate(a) builds running totals

Common mistakes

  • Off-by-one errors from mixing inclusive and exclusive indexes.
  • Using prefix sums when the array is updated often; use a Fenwick tree instead.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1With p = [0, 3, 4, 8, 9], what is the sum of a[1..3]?

Question 2

2After O(n) preprocessing, what does each range-sum query cost?

Question 3

3Why use prefix sums with a hash map instead of a sliding window for "count subarrays with sum k"?

Question 4

4The array changes after every query. Why are plain prefix sums a poor fit?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write pivot_index(a) that returns the first index where the sum of items to the left equals the sum to the right, or -1. Example: [1, 7, 3, 6, 5, 6] returns 3 (1+7+3 = 5+6).

  2. Exercise 2medium

    Write count_subarrays(a, k) returning how many contiguous subarrays sum to exactly k. Numbers can be negative. Example: [1, 1, 1], k = 2 returns 2; [3, 4, -7, 3], k = 3 returns 3.

  3. Exercise 3hard

    Write product_except_self(a) that returns a list where out[i] is the product of every item except a[i], without division, in O(n). Example: [1, 2, 3, 4] returns [24, 12, 8, 6].

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do prefix sums work for products or maximums?
Products work if there are no zeros (or you handle them), using division instead of subtraction. Maximums do not, because you cannot "subtract" a max; use a sparse table or segment tree.
Should the prefix array have n or n + 1 items?
Use n + 1 with a leading zero. Every range sum then uses one formula with no special cases.
What is the difference between prefix sums and a sliding window?
Prefix sums answer any range after preprocessing and handle negatives. A sliding window walks one range along the array and needs a rule like all numbers being positive.

Go deeper

ShareXLinkedInWhatsApp