The prefix sum pattern, with templates

The prefix sum pattern precomputes running totals so that the sum of any contiguous range becomes one subtraction: with prefix[i] holding the sum of the first i values, the sum from index l to r is prefix[r + 1] - prefix[l]. Building the array takes O(n), and every range query after that is O(1). Combined with a hash map it answers questions about subarrays with a target sum, and its relatives (2D prefix sums, difference arrays, prefix XOR and prefix mod m) cover grid regions, batches of range updates and divisibility.

By Published 8 min read

The idea in one picture

Take the array [3, -1, 4, -2, 2, 1]. Its prefix array, with a leading zero, is [0, 3, 2, 6, 4, 6, 7]: each entry is the total of everything before that position. The sum of a stretch is the total up to its end minus the total before its start. For indices 1 to 3 (the values -1, 4 and -2), that is prefix[4] - prefix[1] = 4 - 3 = 1. For indices 2 to 4 it is 6 - 2 = 4. No loop over the stretch is needed.

Why the leading zero? It stands for the empty prefix, so a range starting at index 0 subtracts prefix[0] = 0 and needs no special case. Every template on this page relies on it in some form.

When to reach for it

Signals in a prompt and the version they point to
SignalVersionWhat you store
Many sum queries over ranges of a fixed arrayPlain 1D prefixAn array of n + 1 totals
Count subarrays whose sum equals kPrefix plus count mapHow often each total has appeared
Longest subarray with sum k, or with equal numbers of two thingsPrefix plus first-seen mapThe earliest index of each total
Subarray sum divisible by mPrefix mod mCounts or first index per remainder
XOR of a range, or a subarray whose XOR is xPrefix XORRunning XOR values
Sum over a rectangle of a grid, many times2D prefixAn (r + 1) by (c + 1) table
Many "add v to positions l through r" updates, read once at the endDifference array+v at l, -v after r
Product of everything except position iPrefix and suffix productsProducts from the left and from the right
Signals in a prompt and the version they point to. Scroll sideways on a small screen.

A useful check: if the question says contiguous and the values can be negative, a sliding window is probably out, because the sum does not grow steadily as the window widens. Prefix sums do not care about signs.

Templates in Python

def build_prefix(nums):
    prefix = [0] * (len(nums) + 1)      # prefix[i] = sum of the first i values
    for i, x in enumerate(nums):
        prefix[i + 1] = prefix[i] + x
    return prefix


def range_sum(prefix, left, right):
    # sum of nums[left..right], both ends included
    return prefix[right + 1] - prefix[left]
Build once in O(n), answer each range sum in O(1).

The hash map variant turns "does some earlier total make this difference" into a lookup. Subarray Sum Equals K walks through the counting version in detail. The template below answers a different question, the length of the longest run with sum k, so it remembers where each total first appeared instead of how often.

def longest_with_sum(nums, k):
    first_seen = {0: -1}      # prefix value -> earliest index where it appeared
    prefix = 0
    best = 0
    for i, x in enumerate(nums):
        prefix += x
        if prefix - k in first_seen:
            best = max(best, i - first_seen[prefix - k])
        if prefix not in first_seen:      # keep the earliest, it gives the longest run
            first_seen[prefix] = i
    return best
Longest subarray with sum k: keep the earliest index of each running total.

On [3, -1, 4, -2, 2, 1] with k = 3, the answer is 4, from the run -1, 4, -2, 2. On [1, 2, -3, 3, 0] with k = 3 it is 5, the whole array. Seeding the map with {0: -1} is what lets a run that starts at index 0 count, and its length comes out as i - (-1) = i + 1.

def build_prefix_2d(grid):
    rows, cols = len(grid), len(grid[0]) if grid else 0
    P = [[0] * (cols + 1) for _ in range(rows + 1)]
    for r in range(rows):
        for c in range(cols):
            P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c]
    return P


def rect_sum(P, r1, c1, r2, c2):
    # sum of grid[r1..r2][c1..c2], corners included
    return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]
2D prefix sums: inclusion and exclusion with a padded first row and column.

For the grid [[2, 0, 1], [3, 5, -1], [4, 1, 2]], the bottom-right 2 by 2 block (rows 1 to 2, columns 1 to 2) sums to 7, and the whole grid to 17. The build formula adds the cell, the total above and the total to the left, then subtracts the overlap that was counted twice. The query does the same in reverse.

def apply_range_adds(n, updates):
    diff = [0] * (n + 1)
    for left, right, amount in updates:   # add amount to positions left..right
        diff[left] += amount
        diff[right + 1] -= amount
    result, running = [], 0
    for i in range(n):
        running += diff[i]                # the prefix sum of diff is the final value
        result.append(running)
    return result
Difference array: O(1) per range update, one pass to read the result.

Applying +5 to positions 0 to 2, -2 to positions 1 to 4 and +1 to positions 3 to 5 on six zeros gives [5, 3, 3, -1, -1, 1]. The diff array marks where each change starts and where it stops, and the running sum spreads it across the range. This is the trick behind booking, car-pooling and "how many events cover each point" questions.

Templates in JavaScript

function buildPrefix(nums) {
  const prefix = new Array(nums.length + 1).fill(0);
  for (let i = 0; i < nums.length; i++) prefix[i + 1] = prefix[i] + nums[i];
  return prefix;
}

function rangeSum(prefix, left, right) {
  return prefix[right + 1] - prefix[left];
}

function countDivisible(nums, m) {
  // subarrays whose sum is a multiple of m
  const seen = new Array(m).fill(0);
  seen[0] = 1;
  let prefix = 0;
  let count = 0;
  for (const x of nums) {
    prefix = (((prefix + x) % m) + m) % m;   // JS % can be negative
    count += seen[prefix];
    seen[prefix] += 1;
  }
  return count;
}

function prefixXor(nums) {
  const px = [0];
  for (const x of nums) px.push(px[px.length - 1] ^ x);
  return px;   // xor of nums[l..r] is px[r + 1] ^ px[l]
}
Range sums, a remainder-count variant and prefix XOR.

Two details in the JavaScript version matter. The remainder operator keeps the sign of the left side, so -4 % 3 is -1, not 2; normalizing with ((p % m) + m) % m keeps remainders between 0 and m - 1 and makes equal remainders match. And XOR undoes itself, so the XOR of a range is the XOR of two prefixes, exactly like subtraction for sums. As a check, [4, -3, 5, -1, 2] has 4 subarrays whose sum is a multiple of 3.

Cost

n values, q queries or updates, an r by c grid
TaskWithout prefix sumsWith themExtra space
q range-sum queriesO(n · q)O(n + q)O(n)
Count or find subarrays with a target sumO(n²)O(n) averageO(n)
q rectangle sumsO(r · c · q)O(r · c + q)O(r · c)
q range updates, then read everythingO(n · q)O(n + q)O(n)
Range sums while values keep changingO(n) per queryO(n) per change to rebuild; a Fenwick tree gives O(log n) for bothO(n)
n values, q queries or updates, an r by c grid. Scroll sideways on a small screen.

Problems that use the pattern

  • [Subarray Sum Equals K](/coding-problems/subarray-sum-equals-k). The count-map version, and the best first problem for the pattern.
  • [Range Sum Query](/coding-problems/range-sum-query). The plain template wrapped in a class, then the version with updates, which needs a Fenwick or segment tree.
  • Longest run with equal numbers of 0s and 1s. Map 0 to -1, then find the longest subarray with sum 0 using the first-seen template.
  • A subarray of length at least 2 whose sum is a multiple of m. Store the first index of each remainder and check that the gap is at least 2.
  • Product of the array except each position. Prefix products from the left times suffix products from the right, with no division.
  • Sum of a rectangle in a matrix, asked many times. The 2D template as written above.

The look-up-what-you-need idea is the same one used in Two Sum; prefix sums apply it to running totals. For range questions about overlaps rather than sums, see the intervals pattern, which uses a difference-array style sweep for its counting variant.

Mistakes

  • Sizing the prefix array n instead of n + 1, then patching the index-0 case by hand and getting it wrong.
  • Mixing inclusive and exclusive ends. Decide on prefix[r + 1] - prefix[l] for an inclusive range and keep it.
  • In the map variants, inserting the current total before looking up the complement, which lets an empty subarray match when k is 0.
  • Overwriting the first-seen index with a later one, which shortens the longest run.
  • Forgetting to normalize negative remainders in JavaScript, C++ or Java.
  • In fixed-width integer languages, overflowing the running total on long arrays of large values.
  • Using a prefix array when the input changes between queries.

How to explain it out loud

Fictional example

Justifying the precomputation
Candidate
There will be many range-sum queries on the same array, so recomputing each one from scratch would cost the length of the range every time.
Candidate
I'll build a prefix array of length n plus one, where entry i is the sum of the first i values and entry zero is zero. Then any range from l to r is the entry after r minus the entry at l.
Interviewer
What if the values change between queries?
Candidate
Then one update could shift every later total, which is linear per change. I'd switch to a Fenwick tree, which gives logarithmic updates and queries.

Drilling the pattern with Natively

Prefix sum questions are easy to recognise and easy to fumble by one index. While you practice, Natively can take a screenshot of the problem on Mac or Windows and show an approach with code in its overlay, which you can hold against your own boundaries and seeding. During a spoken mock it writes down what you said, so you can check later whether you explained why the leading zero is there. Details are on the AI interview assistant page.

Questions people ask

What is the prefix sum technique?

Build an array where entry i holds the sum of the first i values, with a 0 in front. The sum of any range l to r is then prefix[r + 1] - prefix[l], so each query is O(1) after O(n) setup.

When should you use prefix sums?

When you need many range sums on data that does not change, or when a subarray condition can be written as the difference of two running totals, such as a target sum or a multiple of m.

What is a difference array?

The reverse of a prefix sum. To add v to positions l through r, add v at l and subtract it after r. One prefix pass at the end gives every final value, so each update is O(1).

Why do prefix sums work with negative numbers when sliding windows do not?

A window needs the sum to change in one direction as it grows. Prefix sums only subtract two totals, so the signs of the values do not matter.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP