Roadmap › Stage 2: Arrays & Strings › Pattern 8 of 53
DSA pattern guide

Array — Prefix Sum

Many range-sum queries, or "subarray sum equals k".

Stage 2 · Arrays & Strings6 problems1 Easy · 5 Medium

Use it when

Many range-sum queries, or "subarray sum equals k".

Key idea

prefix[i] = sum up to i, so any range sum is prefix[r] − prefix[l−1]. Pair it with a hashmap to count subarrays hitting a target.

Practice problems, in order

  1. Find Pivot IndexEasy
  2. Subarray Sum Equals KMedium
  3. Matrix Block SumMedium
  4. Product of Array Except SelfMedium
  5. Continuous Subarray SumMedium
  6. Subarray Sum Divisible by KMedium

How to practise this pattern

  1. Read the problem and look for the signal above before writing any code.
  2. Say the brute force out loud, with its time complexity, then ask what work it repeats.
  3. Apply the key idea and write the optimised version yourself.
  4. If you're stuck for more than 10 minutes, take one small hint, not the full solution.
  5. Move to the next problem only when you can explain why this pattern fits.

Stuck on one of these?

The AlgoSolveo extension (free, launching soon) sits beside the LeetCode problem and gives the smallest hint that gets you moving, never the full answer. Solved problems tick off on your roadmap.

Join the extension waitlistTrack it on the roadmap
← Previous patternArray — Sliding WindowNext pattern →Array — Kadane's Algorithm