← All templates

Prefix Sum

Pro

Use when you need to efficiently compute range sums, find subarrays with a target sum, or answer multiple cumulative queries on an array.

Use when you need to efficiently compute range sums, find subarrays with a target sum or property, or answer multiple cumulative queries on an array.

Keywords for identifying Prefix Sum Problems

β†’ Range sum / subarray sum query
β†’ Find subarray with target sum / divisible by k
β†’ Contiguous subarray with property (equal count, sum equals k)
β†’ Product of array except self
β†’ Multiple range queries on same array
β†’ Cumulative sum / running total

Unlock the Prefix Sum template

Get the full code template and worked LeetCode examples for Prefix Sum β€” plus every other pattern in the library β€” with a one-time $29 lifetime upgrade.

Upgrade to ProSee free Binary Search template β†’
Prefix Sum Β· Templates Β· Grind Patterns