Skip to content
DSA in JavaScript
← All patterns

Prefix Sum

0/15 solved

What it is

Write down a running total once, then answer "what is the sum of this range?" with one subtraction instead of re-adding.

Used for

Many range-sum questions on the same array, counting subarrays with a target sum.
numbers

Step 1 of 5

Question: what is 1 + 4 + 2? Adding three numbers is easy. But if someone asks 1,000 range questions, you re-add the same numbers again and again.

You see

  • Many range-sum queries on a static array
  • Subarray sum equals k
  • Product or count of everything except self

Learn it in

ArraysMaximum subarray problemFenwick Tree / Binary Indexed TreeSegment Tree

Template

// Running totals: prefix[i] = nums[0] + ... + nums[i - 1], with prefix[0] = 0.const prefix = [0];for (const n of nums) prefix.push(prefix.at(-1) + n);const rangeSum = (start, end) => prefix[end + 1] - prefix[start]; // nums[start..end]// Variant: count subarrays that add up to k, using a Map of running totals seen so far.function subarraySum(nums, k) {  const count = new Map([[0, 1]]);  let sum = 0, hits = 0;  for (const n of nums) {    sum += n;    hits += count.get(sum - k) ?? 0;    count.set(sum, (count.get(sum) ?? 0) + 1);  }  return hits;}

Practice problems