Interview concept

What are prefix sums?

A prefix sum stores the cumulative total up to each index, so the sum of any subarray is the difference of two prefix values. It turns repeated range-sum queries from O(n) each into O(1) after O(n) preprocessing.

Interview concept

How it works

How it works

Build an array where each entry holds the sum of all earlier elements, then subtract endpoints for a range.

Two dimensions

A 2D prefix sum answers submatrix-sum queries in constant time using inclusion and exclusion.

Related patterns

Prefix XOR, prefix counts, and difference arrays extend the same idea.

Interview concept

Responsible use

Use any live AI assistant only where interview, workplace, school, and platform rules allow it. Do not use generated answers to misrepresent your skills, experience, or authorship.

FAQ

Common questions.

When are prefix sums useful?

When you answer many range-sum or range-count queries over static data, or need subarray sums quickly.

What is a difference array?

It is the inverse idea: record deltas at range endpoints, then take a prefix sum to apply many range updates efficiently.