Patterns

Concept shape

Practice pattern
0
1
2
3
4
5
Definition

Store cumulative totals so range queries can be answered quickly.

Step 1 / 5
Concept shape
Current lesson

Prefix Sums Lab

Patterns Practice pattern

Prefix Sums

Welcome to the Prefix Sums concept lab. Store cumulative totals so range queries can be answered quickly. The must know points are: Range sum equals prefix[right + 1] - prefix[left]. Works for arrays and grids. Hash maps combine well with prefix sums. The common operations are: build prefix, range query, track seen prefix. The complexity shape is Build O(n), query O(1). Watch out for these pitfalls: Off-by-one errors. Forgetting prefix[0] = 0. Related algorithms include Subarray Sum Equals K, Range Sum Query.

Concept details

Store cumulative totals so range queries can be answered quickly.

Must know

  • Range sum equals prefix[right + 1] - prefix[left].
  • Works for arrays and grids.
  • Hash maps combine well with prefix sums.

Complexity

Build O(n), query O(1)

Open deeper visual structure lesson
1.0x