Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Arrays & Two Pointers

Prefix Sum

O(n)

Store cumulative sums; the sum of any range is a subtraction. Pair with a hashmap of seen prefixes to count subarrays.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksDifference Array & Line SweepSegment Tree / Fenwick (BIT)Square Root DecompositionSum over Subsets (SOS) DP+3
0%
mastery
0/51 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Many range-sum queries on a static array, or count subarrays with sum/xor/mod = k (negatives OK), or balance problems (map 0 to -1).

  1. 1Brute force

    Sum each queried range in O(n); or check all O(n2) subarrays.

  2. 2The observation

    Repeated summation: sum(l..r) = P[r+1] - P[l] in O(1); subarray conditions become 'find earlier prefix with value P - k' (hash map).

  3. 3Why it works

    P[i] = sum of the first i elements, so subarray (l, r] sums to P[r] - P[l]; count pairs of prefixes with a hashmap.

Reach for it when

  • +Many range-sum queries on a static array → precompute once, answer each in O(1).
  • +Count / find subarrays with sum = k, sum divisible by k, or equal #0s and #1s.
  • +You spot an O(n²) double loop computing sums of ranges that overlap heavily.

Not when

  • ×The array is updated between queries; prefix sums go staleuse Fenwick tree or segment tree
  • ×Longest/shortest window under a constraint and all numbers are positiveuse Sliding window: simpler, O(1) space
  • ×Range min/max: not invertible, no subtraction trickuse Sparse table
  • ×Range products with zeros: division is undefineduse Prefix product with explicit zero handling

Intuition

A prefix sum is a running total. pre[i] = the sum of everything before index i. If the array is [2, 4, 1, 3], the prefixes are [0, 2, 6, 7, 10] (start with 0, then keep adding).

Read the full intuition

Why bother? Because the sum of any slice [i, j) becomes a single subtraction: pre[j] - pre[i]. The cost of summing a range drops from "walk the whole range" to one operation. It's the same idea as a bank balance: to know how much you spent between Tuesday and Friday, you subtract Tuesday's balance from Friday's.

The real superpower is prefix sum + hash map for "count subarrays whose sum is k". A subarray (i, j] has sum k exactly when pre[j] - pre[i] = k, i.e. pre[i] = pre[j] - k. So as you sweep and compute each running sum, you ask the map: "how many earlier prefixes equalled (current - k)?" — each is a valid subarray ending here.

Walk [1, 2, 3], k = 3. Map starts {0: 1} (the empty prefix).

  • sum=1. Need 1-3=-2. Not in map. Store {0:1, 1:1}.
  • sum=3. Need 3-3=0. Map has 0 once → +1 subarray ([1,2]). Store 3.
  • sum=6. Need 6-3=3. Map has 3 once → +1 subarray ([3]). Total 2. ✓

Key idea

The {0: 1} seed is essential — it accounts for subarrays that start at index 0 (whose left prefix is the empty sum).

Why it costs what it costs

Time O(n). single pass; each prefix is computed and looked up in O(1) amortised via the hash map.

Space O(n). the map can hold up to n distinct prefix values (or the prefix array itself).

Practice

Next · Foundation

Running Sum of 1d Array

P[i] = P[i-1] + a[i]; everything else builds on this.

0/51 solved
  • Running Sum of 1d ArrayFoundationFoundationAmazon, AdobeEasy
  • Range Sum Query - ImmutableApply it · Answer many range sums.Apply itMeta, AmazonEasy
  • Find Pivot IndexOne change · Compare left and right sums at each index.One changeMeta, AmazonEasy
  • Product of Array Except SelfTwists · Division is forbidden and zeros exist.TwistsMeta, AmazonMedium
  • Subarray Sum Equals KBranches · Count subarrays instead of answering ranges.BranchesMeta, AmazonMedium
  • Contiguous ArrayBranches · Map 0 to -1 so 'balanced' means sum 0; store FIRST index.BranchesMeta, AmazonMedium
  • Subarray Sums Divisible by KBranches · Key on prefix mod k.BranchesCitadel, AmazonMedium
  • Continuous Subarray SumBranches · Length must be at least 2.BranchesMeta, AmazonMedium
  • Range Sum Query 2D - ImmutableAdvanced · Extend to two dimensions.AdvancedMeta, GoogleMedium
  • Count of Range SumMastery checkMastery checkHard
  • Maximum Size Subarray Sum Equals kPremiumMedium
  • Shortest Subarray with Sum at Least KGoldman Sachs, CitadelHard

Pitfalls

Classic bugs

  • !Forgot the {0: 1} seed: you miss every subarray starting at index 0.
  • !Off-by-one: P has n+1 entries and P[j+1] - P[i] is nums[i..j] inclusive. Pick one convention and keep it.
  • !Negative mod: -1 % k can be negative in C++/Java/JS. Normalise with ((x % k) + k) % k.
  • !Insert the current prefix into the map after querying its complement, or you count a length-0 subarray.
  • !Running sum overflows int on big arrays in C++/Java: use long.
Go deepervariants and techniques · 14 combinations · resources

Variants and techniques

  • 2D Prefix SumsExtend prefix sums to grids with inclusion-exclusion so any sub-rectangle sum is O(1).
  • Static range queriesBuild pre[] once; answer each query in O(1) by subtraction. Range Sum Query - Immutable, 2D variant for matrices.
  • Count sum = kHash map of prefix → frequency; add seen[cur-k] each step. Subarray Sum Equals K.
  • Divisible by k / same remainderBucket prefixes by remainder mod k; equal remainders bracket a divisible subarray. Subarray Sums Divisible by K.
  • Map values to ±1Turn a balance condition (equal 0s and 1s) into 'longest subarray with sum 0' by treating 0 as -1. Contiguous Array.
  • Prefix productProduct Except Self uses prefix & suffix products instead of sums (watch for zeros).

Combinations

  • Prefix Sum+Hash Map / Hash Set Lookup

    count/longest subarrays with sum (or mod, or balance) equal to a target, negatives allowed

    Prefix Sum:
    turns every subarray into a pair of prefixes
    Hash Map / Hash Set Lookup:
    counts earlier prefixes with the needed value in O(1)

    Subarray Sum Equals KContiguous ArraySubarray Sums Divisible by K

  • Prefix Sum+Monotonic Deque

    shortest subarray with sum >= K when values can be negative; max subarray sum with length in [a, b]

    Prefix Sum:
    subarray sums as prefix differences
    Monotonic Deque:
    keeps increasing prefix candidates for the left end

    Shortest Subarray with Sum at Least KMaximum Subarray Sum II

  • Binary (XOR) Trie+Prefix Sum

    maximum XOR of a subarray

    Binary (XOR) Trie:
    maximises XOR with an earlier prefix
    Prefix Sum:
    subarray XOR = prefix XOR pair

    Maximum Xor Subarray

  • Tree DFS (Paths & Recursion)+Prefix Sum+Hash Map / Hash Set Lookup

    count downward paths with a given sum

    Tree DFS (Paths & Recursion):
    walks root-to-node paths
    Prefix Sum:
    path sums as prefix differences
    Hash Map / Hash Set Lookup:
    counts prefix values on the current path

    Path Sum III

  • Divide & Conquer DP Optimisation+Prefix Sum

    split array into k parts minimising sum of squared/segment costs

    Divide & Conquer DP Optimisation:
    monotone split points per layer
    Prefix Sum:
    O(1) segment cost

    Subarray Squares

  • Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup

    count subarrays in [l, r] with a pair property, many offline queries

    Mo's Algorithm (offline range queries):
    moves the query window
    Prefix Sum:
    subarray XOR as prefix XOR pair
    Hash Map / Hash Set Lookup:
    frequency counts of prefix values in the window

    XOR and Favorite Number

  • Prefix Sum+Bit Tricks & Bitmasking+Hash Map / Hash Set Lookup

    substrings/subarrays where every letter (or bit) occurs an even number of times, or at most one is odd

    Prefix Sum:
    a substring's parity is prefix[j] ^ prefix[i]
    Bit Tricks & Bitmasking:
    a parity mask of the character counts replaces a count vector
    Hash Map / Hash Set Lookup:
    first index (or count) of each mask seen so far

    Find the Longest Substring Containing Vowels in Even CountsNumber of Wonderful SubstringsCount the Number of Beautiful Subarrays

  • FFT / NTT Convolution (and Walsh-Hadamard)+Prefix Sum

    for every k, the number of subarrays with exactly k elements satisfying a predicate

    FFT / NTT Convolution (and Walsh-Hadamard):
    convolve the count array with its reverse to count subarrays with exactly k good elements, for all k
    Prefix Sum:
    count the prefixes having each number of 'good' elements

    Nikita and Order Statistics

  • Bounded (Multiple) Knapsack+Prefix Sum

    count multisets/ways with per-type limits and a bounded sum

    Bounded (Multiple) Knapsack:
    group equal values with their counts
    Prefix Sum:
    window sums along each residue class give dp_new[s] = sum of dp[s - j*v] for j <= c

    Count of Sub-Multisets With Bounded SumNumber of Ways to Earn Points

  • Randomised Set Hashing (XOR / sum hashing, Zobrist)+Prefix Sum+Two Pointers

    subarrays that are permutations, or where every value occurs exactly k times

    Randomised Set Hashing (XOR / sum hashing, Zobrist):
    random labels make set identity additive
    Prefix Sum:
    a subarray's hash is a prefix difference/XOR
    Two Pointers:
    keep the window where no value exceeds k occurrences (1418G)

    The Number of SubpermutationsThree Occurrences

  • Interactive Problems (query-limited search)+Prefix Sum

    find the single altered element using range-sum queries within log n queries

    Interactive Problems (query-limited search):
    query a range sum and compare to binary search for the heavier element
    Prefix Sum:
    know the expected sum of any range

    Interview

  • Monotonic Stack+Contribution Technique (sum over all subarrays/pairs)+Prefix Sum

    sum over all subarrays of min * sum (or similar products)

    Monotonic Stack:
    previous/next smaller bounds for each element
    Contribution Technique (sum over all subarrays/pairs):
    each element is the min of all subarrays inside its bounds
    Prefix Sum:
    prefix sums of prefix sums give those subarrays' total sum in O(1)

    Sum of Total Strength of Wizards

  • Grid / Matrix DP+Prefix Sum

    row DP where moving between columns costs |j - k|

    Grid / Matrix DP:
    row-by-row DP
    Prefix Sum:
    left-to-right and right-to-left running maxima of prev[k] +/- k remove the |j - k| term

    Maximum Number of Points with Cost

  • Harmonic Lemma & Quotient Blocks+Prefix Sum

    sum over pairs of floor(a_i / a_j) with values <= 1e5

    Harmonic Lemma & Quotient Blocks:
    for each divisor value d and each multiple k*d, the count of x in [k*d, (k+1)*d) contributes k
    Prefix Sum:
    counts of values in a range in O(1)

    Sum of Floored Pairs

Resources

  • Two PointersUSACO Guide · course
  • Prefix SumsUSACO Guide · course
  • More on Prefix Sums (difference arrays)USACO Guide · course
  • Array cheatsheetTech Interview Handbook · article
  • NeetCode RoadmapNeetCode · sheet
  • Array and String explore cardLeetCode · course
Sliding WindowCyclic Sort
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial