Chapter 10 - Prefix Sums
Precompute running sums once, then answer any range sum in constant time.
This page is the entry point of chapter 10 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
With prefix[i] the sum of the first i elements, the sum between two indexes is a single subtraction. Combined with a hash map of the prefix sums already seen, it counts the subarrays that sum to k in one pass. The same idea works with products: prefix and suffix products give the product of all the other elements without division.
The chapter also has an introduction page with my notes on the key ideas and a checklist.
When to reach for it
- Many range sum queries on the same array.
- Count or find subarrays whose sum equals a target.
- “Product of all elements except the current one” questions.
In Rust
- A prefix array of length
n + 1that starts with0removes the special case of ranges starting at index 0. iter().scan(0, |acc, &x| { *acc += x; Some(*acc) })builds the running sums.- Use
i64for the sums when the inputs arei32: sums overflow long before single values do.
Problems in this chapter
- p175 - Introduction: Introduction to the Prefix Sums pattern for coding interviews, in Rust: the key idea, when to use it, and the problems of the chapter.
- p177 - Sum Between Range: Sum Between Range (Prefix Sums), solved in Rust. Given an array of i32 return the sum of vals between 2 indexes. You can assume.
- p180 - K-Sum Subarray: K-Sum Subarray (Prefix Sums), solved in Rust. Find the number of subarrays in an array of i32 that sum to k.
- p184 - Product Array Without Current Element: Product Array Without Current Element (Prefix Sums) solved in Rust: result[i] is the product of all the elements except nums[i].
Other chapters
All the chapters, with every problem, are listed on the series page.