Skip to main content
Prefix Sum Pattern

What is Prefix Sum?

Prefix Sum (cumulative sum) is a preprocessing technique that stores running totals, enabling O(1) range sum queries after O(n) preprocessing.
Quick Recognition: Problems involving range sums, subarray sums with target, or cumulative calculations. Keywords: “sum of range”, “subarray sum equals k”, “cumulative”.

Pattern Recognition Checklist

Use Prefix Sum When

  • Multiple range sum queries
  • Finding subarray with specific sum
  • Equilibrium/pivot index problems
  • 2D matrix region sums
  • Running totals with modifications

Don't Use When

  • Single range query (just iterate)
  • Array values change frequently (use Segment Tree)
  • Need min/max in range (use Segment Tree)
  • Need product (use prefix product)

When to Use

Range Sum Queries

Sum of elements in any range

Subarray Sum Problems

Find subarrays with specific sum

Equilibrium Index

Where left sum equals right sum

2D Range Sum

Sum in rectangular region

Core Concept

Pattern Variations

1. Basic Range Sum

2. Subarray Sum Equals K

3. Product of Array Except Self

4. 2D Prefix Sum (Matrix Region Sum)

Classic Problems

Interview Problems by Company

Interview Tips

Range sum [i, j] = prefix[j+1] - prefix[i]Why j+1? Because prefix[k] = sum of first k elements (0 to k-1).So prefix[j+1] = sum of elements 0 to j And prefix[i] = sum of elements 0 to i-1Difference = sum of elements i to j
For “count subarrays with sum = k”:
Build: prefix[i+1][j+1] = matrix[i][j] + prefix[i][j+1] + prefix[i+1][j] - prefix[i][j]Query: sum(r1,c1 to r2,c2) = prefix[r2+1][c2+1] - prefix[r1][c2+1] - prefix[r2+1][c1] + prefix[r1][c1]

Practice Problems

Range Sum Query

Basic prefix sum

Subarray Sum K

HashMap with prefix

Contiguous Array

Transform and prefix

2D Range Sum

2D prefix sum

Practice Roadmap

1

Day 1: Basic Prefix Sum

  • Solve: Range Sum Query, Running Sum
  • Focus: Building and querying prefix array
2

Day 2: HashMap + Prefix

  • Solve: Subarray Sum = K, Contiguous Array
  • Focus: Tracking prefix counts
3

Day 3: 2D Prefix Sum

  • Solve: 2D Range Sum Query
  • Focus: Inclusion-exclusion principle
4

Day 4: Variations

  • Solve: Product Except Self, Maximum Subarray
  • Focus: Prefix products, Kadane’s
Interview Tip: When you see “sum of subarray” or “range sum query”, think Prefix Sum. Add HashMap when counting subarrays with specific sum.