Command Palette

Search for a command to run...

Module 5

Prefix Sum

Precompute running totals once, and every range question becomes a subtraction. Add a hash map and you can count subarrays with any target sum.

Beginner 4 lessons 7 problems ~50 min of lessons

A prefix sum array stores, for each position, the total of everything before it. With it, the sum of any range is one subtraction instead of a loop, which turns many O(n²) problems into O(n).

The module builds from plain range sums to the most important interview variant, prefix sums with a hash map (counting subarrays that sum to k, even with negative numbers), then difference arrays for range updates and 2D prefix sums for grids.

Best after: Hashing

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Precompute once, answer many: O(n + q) instead of O(n · q).

  2. Use the total to get the right-side sum for free: right = total − left − nums[i].

  3. Prefix and suffix products: the answer at i is (product of everything left) × (product of everything right), without division.

  4. Count subarrays with sum k, even with negative numbers, by counting earlier prefix sums equal to sum − k.

  5. Turn "equal 0s and 1s" into "sum zero" by counting 0 as −1, then find the longest zero-sum subarray with first-seen indexes.

  6. Apply many range additions in O(1) each with a difference array, then one prefix sum.

  7. 2D prefix sums: any rectangle's sum with four lookups using inclusion-exclusion.