Skip to the content

Lesson 127 of 296

Prefix sums

What you will learn

  • What a prefix sum array is
  • Answering range sum questions in O(1)
  • Range Sum Query
  • Subarray Sum Equals K with a hash map
  • Find Pivot Index
On this page

The idea

A prefix sum at position i is the total of all items before i.

nums:    [3, 1, 4, 1, 5]
prefix: [0, 3, 4, 8, 9, 14]

prefix[0] = 0, and prefix[i + 1] = prefix[i] + nums[i]. The prefix array has one extra slot at the start so the maths is simpler.

The sum of nums[i..j] (inclusive) is:

prefix[j + 1] - prefix[i]

Sum of indexes 1 to 3 (1 + 4 + 1 = 6): prefix[4] - prefix[1] = 9 − 3 = 6.

Building the prefix array is O(n) once. After that, every range sum is O(1).

Range Sum Query

Problem (LeetCode 303): many queries sumRange(left, right) on the same array.

TypeScript
class NumArray {
  private prefix: number[];

  constructor(nums: number[]) {
    this.prefix = new Array<number>(nums.length + 1).fill(0);
    for (let i = 0; i < nums.length; i++) {
      this.prefix[i + 1] = this.prefix[i]! + nums[i]!;
    }
  }

  sumRange(left: number, right: number): number {
    return this.prefix[right + 1]! - this.prefix[left]!;
  }
}

O(n) to build, O(1) per query, O(n) space. Without it, every query would be O(n).

(If the array also changes between queries, a Fenwick tree or segment tree is used; good to name for senior roles.)

Subarray Sum Equals K

Problem (LeetCode 560): count the contiguous subarrays whose sum is exactly k. Numbers can be negative.
nums = [1, 1, 1], k = 2 → 2.

Sliding window does not work here, because with negative numbers, growing the window does not always increase the sum.

Idea: a subarray from i to j sums to k exactly when prefix[j + 1] - prefix[i] = k, which means prefix[i] = currentPrefix - k. So, walking left to right, count how many earlier prefix sums equal currentPrefix - k. Store prefix sum counts in a Map (Lesson 122).

TypeScript
function subarraySum(nums: number[], k: number): number {
  const prefixCounts = new Map<number, number>([[0, 1]]);
  let current = 0;
  let count = 0;
  for (const num of nums) {
    current += num;
    count += prefixCounts.get(current - k) ?? 0;
    prefixCounts.set(current, (prefixCounts.get(current) ?? 0) + 1);
  }
  return count;
}

[[0, 1]] at the start means "an empty prefix with sum 0 exists once", so subarrays starting at index 0 are counted.

Trace [1, 1, 1], k = 2:

numcurrentlooking for current − kfoundcountmap after
11-100{0:1, 1:1}
12011{0:1, 1:1, 2:1}
13112{0:1, 1:1, 2:1, 3:1}

O(n) time, O(n) space. This "prefix sum + hash map" combination is one of the most valuable patterns to know.

Find Pivot Index

Problem (LeetCode 724): the first index where the sum of items on the left equals the sum on the right.

TypeScript
function pivotIndex(nums: number[]): number {
  const total = nums.reduce((a, b) => a + b, 0);
  let leftSum = 0;
  for (let i = 0; i < nums.length; i++) {
    const rightSum = total - leftSum - nums[i]!;
    if (leftSum === rightSum) return i;
    leftSum += nums[i]!;
  }
  return -1;
}

O(n) time, O(1) space.

Variations

  • 2D prefix sums answer rectangle sums in a grid in O(1).
  • Prefix XOR, prefix counts, prefix products (Lesson 118) follow the same idea.

How to say it in an interview

"A prefix sum array stores running totals with a leading zero, so any range sum is prefix of right plus one minus prefix of left in O(1) after an O(n) build. For Subarray Sum Equals K, which allows negatives so sliding window fails, I keep a running sum and a map of how many times each prefix sum has occurred, starting with zero once; at each step I add the count of current minus k. That is O(n) time and space."

Key words

WordMeaning
Prefix sumThe total of all items before a position
Range queryA question about a range, such as its sum
Running sumA total updated as you go

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.