Arrays

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Store cumulative totals so range sums are answered by subtraction.

Step 1 / 5
Problem shape
Current lesson

Prefix Sum Lab

Arrays Beginner

Prefix Sum

Welcome to the Prefix Sum algorithm lab. Store cumulative totals so range sums are answered by subtraction. Use it when: Use when many range-sum queries or subarray-sum checks are needed. The time complexity is O(n) build, O(1) query, and the space complexity is O(n). The pseudocode is: prefix[0] = 0 for i from 0 to n - 1 prefix[i + 1] = prefix[i] + a[i] sum(l, r) = prefix[r + 1] - prefix[l] As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n) build, O(1) query

Space

O(n)

Pseudocode

prefix[0] = 0
for i from 0 to n - 1
  prefix[i + 1] = prefix[i] + a[i]
sum(l, r) = prefix[r + 1] - prefix[l]
Open deeper structure lesson
1.0x