Pattern

Prefix sums

Precompute running totals so any range sum, or any question phrased as one, answers in O(1) instead of a rescan.

What it is

A prefix sum array stores, at each index, the running total of everything up to that point. Once you have it, the sum of any subarray is one subtraction away (prefix[j] - prefix[i]) instead of a fresh scan. The technique's reach goes well beyond literal sums: a lot of "count subarrays with property X" questions become prefix-sum questions once you find the right transformation — turning 0/1 into -1/1 to talk about balance, or reducing to "does a subarray sum to a multiple of k" via remainders. Paired with a hash map of prefix values seen so far, it turns an O(n²) subarray-counting scan into O(n).

When it applies

Tells in the problem

The classic mistake

The failure interviewers report most is computing the running sum correctly but then re-deriving each subarray sum with a fresh inner loop anyway — effectively building the prefix array and never using it, which quietly leaves the solution at O(n²). This happens because the insight "sum(i..j) = prefix[j] - prefix[i-1]" is easy to state but easy to forget to actually apply once the code is mid-write, especially once a hash map or an off-by-one on the prefix index enters the picture. The second, more subtle version of this mistake is getting the prefix's off-by-one wrong when counting subarrays with a hash map — forgetting to seed the map with {0: 1} for the empty prefix, which silently drops every subarray that starts at index 0.

Questions to start with

All 7 prefix sums questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.