BeginnerAbout 15 min
Prefix Sum
Read the full article on Substack
7 min read.
Learn the Prefix Sum technique to answer range sum queries in O(1) time. Visualize how pre-computation transforms the array.
Think of it this way: Think of a running total on a receipt. If you want to know how much you spent on items 5 through 10, you don't sum them up again. You just take the running total at item 10 and subtract the running total at item 4.
prefix[0] = 0: the sum of nothing.
1/9
Check your understanding
Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.
Build the prefix array
Schematic
For a = [3, 1, 4, 1, 5], fill in P where P[i] is the sum of the first i elements.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
0
P[0]
P[1]
P[2]
P[3]
P[4]
P[5]
5 pieces left to place
Quiz
20 questionsQuestion 1 of 20
Score: 0
What is the time complexity of a Range Sum Query AFTER building the prefix sum array?
Done with this lesson?
Sign in free to keep your progress, streak and quiz scores.