functionsPrefix Sum

Prefix Sum: when to spot it, explain it, and practice it

Prefix sum is the simplest way to stop recomputing overlapping ranges. The pattern becomes especially powerful when the prefix is paired with a hash map to count or locate target differences.

Pattern coverage

35+

Best first move

Pick whether you need a raw prefix array or prefix + hash map.

Common failure point

Inclusive/exclusive indices are mixed up.

When this pattern should come to mind

The problem asks for many range sums or counts over ranges.
The answer depends on the difference between two cumulative states.
Subarray target conditions can be rewritten as prefix[j] - prefix[i] = target.

Checklist before you code

Pick whether you need a raw prefix array or prefix + hash map.
Use a leading zero when you want range math to stay clean.
Be explicit about whether indices are inclusive or exclusive.
For modulo problems, normalize negative values carefully.

The solving flow that works well in interviews

1

Define what the cumulative state means.

2

Build the prefix in one forward pass.

3

Rewrite the target condition into a difference of prefix states.

4

If counting, store prior prefixes in a map before or after checking based on the problem.

5

Use the derived difference to update the answer in O(1) per step.

Common variants

Range query

Use prefix arrays to answer repeated range-sum questions quickly.

Prefix + hash map

Count or locate subarrays by looking up prior prefix states.

2D prefix sum

Compress rectangle-sum queries in matrices.

Template preview

PythonPublic preview
prefix = [0] * (len(nums) + 1)
for i, value in enumerate(nums):
    prefix[i + 1] = prefix[i] + value

range_sum = prefix[r + 1] - prefix[l]

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Inclusive/exclusive indices are mixed up.

warning

Hash-map update timing is wrong for count-based problems.

warning

Modulo keys are not normalized, breaking lookups.

warning

Using prefix sum where a sliding window is required for all-positive constraints.

Recommended practice path

1

Start with range sum query and immutable arrays.

2

Then solve subarray sum equals k.

3

Add modulo-based prefix questions next.

4

Finish with tree or matrix prefix-sum variants.

Prefix Sum Pattern Guide | LeetCode Interview Prep - Interview AiBox