Browse curriculum

Prefix Sum

The Prefix Sum Pattern

Precompute cumulative totals once, then answer any range-sum query as the difference of two prefix values. Pairing prefix sums with a hash map turns "count subarrays summing to k" into a single pass.

4

Interactive problems

1

Free to open

Recognise

How do you recognise a prefix sum problem?

The problem asks about sums or counts over many subarrays or ranges, especially with repeated queries over unchanging data. "Subarray sum equals k" and "range sum query" are the standard forms.

Complexity

What is the time complexity of the prefix sum pattern?

O(n) preprocessing, then O(1) per range query — against O(n) per query when summing directly.

Problems

Prefix Sum practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Prefix Sum problems by difficulty and complexity

The difficulty, running time and extra space of every prefix sum solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to Prefix SumsEasyΩ(N + Q)Θ(N + Q)O(N + Q)O(N)
Count Vowels in RangesMediumΩ(N + Q)Θ(N + Q)O(N + Q)O(N + Q)
Product of Array Except SelfMediumΩ(n)Θ(n)O(n)O(1)
Subarray Sum Equals KMediumΩ(N)Θ(N)O(N)O(N)
Curriculum

The underlying technique is covered from first principles in the prefix sum lesson in the DSA visualizer curriculum. Prefix Sum is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern