Visualized DSA Strategies
Episode 3 Prefix Sums
Episode 3Prefix Sums
▶ This video is coming to YouTube soon.
The complete guide to prefix sums for coding interviews, in C++. First how a prefix array is built and why it has one extra slot; the four questions a running total answers; what each approach costs; the C++ for prefix and difference arrays (vector, partial_sum, accumulate, and long long, because signed overflow is undefined behaviour); and five traps. Then nine types, each worked as a small problem in full: examples, the brute force animated beside the running line of code, the complete code, every line explained, and the prefix-sum solution the same way.
What you'll learn
- How a prefix array turns any range sum into one subtraction
- Why the array has n + 1 slots and starts with 0
- Left total against right total with a running sum
- Counting subarrays that sum to k with a prefix map
- Prefix remainders and balances: the same prefix twice means a range between
- Prefix and suffix products without division
- A difference array for many range updates
- 2D prefix sums and the four-corner formula
- Running maximums from both sides: trapping rain water
Chapters
- 0:00Intro
- 0:27Build a prefix array
- 1:49Four questions prefix sums answer
- 2:26What each approach costs
- 3:11Prefix sums in C++
- 4:57Five traps
- 6:00Nine prefix-sum types
- 6:43Type 1 · Sum of a range, many times
- 12:38Type 2 · Where the two sides balance
- 19:05Type 3 · Count subarrays that add to k
- 25:36Type 4 · A subarray that's a multiple of k
- 32:33Type 5 · Equal zeros and ones
- 39:36Type 6 · Product of everything else
- 46:30Type 7 · Many range updates, one sweep
- 53:02Type 8 · The sum of a rectangle
- 59:52Type 9 · How much rain is trapped
- 1:06:33Spot the type
- 1:07:21Quiz: which type?
- 1:08:09Recap
Quiz: test yourself
The 5 questions from the end of the episode. Pick an answer to see why it's right.