Lesson 5 of 5
Prefix sums
Keep a running total at every position and the sum of any stretch of a list becomes one subtraction. Add a dict that counts the totals seen so far, and one walk counts every stretch that adds up to a target.
Build a prefix sum list with a 0 in front and say what each entry holds
Answer any range sum with one subtraction, with the indexes right
Write a class whose constructor builds a notebook once and whose method reads it on every call
Count the subarrays that add up to k with a running total and a dict of totals seen so far
Build prefix and suffix products to get the product of everything except each item
Say the walk, notebook, promise and cost of each one out loud
A dashboard shows orders for five days: [4, 2, 5, 1, 3], days 0 to 4. People pick a stretch of days and the dashboard shows its total. Days 1 to 3: 2 + 5 + 1 = 8. Days 0 to 2: 11. Day 4 alone: 3.
Each answer is a short loop. The trouble is that the questions never stop, and every loop adds up days that earlier questions already added. A year of data and thousands of questions means the same additions done over and over.
This lesson does the adding once. Keep a running total at every position, and the total of any stretch becomes one subtraction. Then the same running totals, with a dict beside them, count every stretch that adds up to a target in a single walk. Last, the same idea with multiplication gives the product of everything except one item.
A running total at every position
What could we write down once so that every later question is cheap? Start from a loop you know. A running total walks the list and adds each item to one name, total. Its promise: after each pass, total is the sum of the items visited so far. When the loop ends, total holds the sum of everything, and every earlier total is gone.
A prefix sum list keeps all of them. A prefix of a list is a run of items from the start: the first item, the first two, the first three. prefix[i] is the sum of the first i items. Count the prefixes carefully: the first 0 items count too. That is the empty prefix, and its sum is 0. So prefix starts with a 0 and ends up one longer than the list.
The trace builds it for the five days. Before you step through, guess the last entry of prefix and how many entries it has.
orders = [4, 2, 5, 1, 3]prefix = [0]total = 0for x in orders:total += xprefix.append(total)print(prefix)
(nothing printed yet)Read the result as a table. Each entry is the sum of the days before its position:
| i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| prefix[i] | 0 | 4 | 6 | 11 | 12 | 15 |
| adds up | nothing | day 0 | days 0 to 1 | days 0 to 2 | days 0 to 3 | days 0 to 4 |
Building it is one walk. For a list of n items that is O(n) time (module 2's notation: the work grows in step with n) and O(n) extra space for the n + 1 totals.
Type exactly what this prints. Watch the negative number.
nums = [3, -2, 5, 1]
prefix = [0]
total = 0
for x in nums:
total += x
prefix.append(total)
print(prefix)
print(len(prefix))
Any range sum is one subtraction
Now the questions. A range sum is the sum of the items from position left to position right, both included. Take days 1 to 3. prefix[4] is 12, the sum of days 0 to 3. prefix[1] is 4, the sum of day 0 alone. Everything through day 3, minus everything before day 1, leaves days 1 to 3: 12 − 4 = 8. By hand, 2 + 5 + 1 = 8.
That gives one rule for every range:
range_sum = prefix[right + 1] - prefix[left]
The + 1 is where off-by-one bugs live (an index one too high or one too low), so say it in words. prefix[i] stops just before position i. To include position right, you need prefix[right + 1]. And prefix[left] stops just before left, which is exactly the part to remove.
The trace answers three questions with that rule: days 1 to 3, days 0 to 2, and day 4 alone. The arrows under orders mark the first and last day asked about. The arrows under prefix mark the two entries the subtraction reads. Before you step, work out the three answers from the table.
orders = [4, 2, 5, 1, 3]prefix = [0, 4, 6, 11, 12, 15]for left, right in [(1, 3), (0, 2), (4, 4)]:end = right + 1print(prefix[end] - prefix[left])
(nothing printed yet)The 0 in front is what makes left = 0 work. The second question subtracted prefix[0], the sum of nothing. A common version stores the running totals without that 0, and then a range that starts at day 0 needs a special case. See what happens when the special case is forgotten:
This version stores the running totals with no 0 in front, so running[i] is the sum of days 0 to i, and a range sum becomes running[right] - running[left - 1].
orders = [4, 2, 5, 1, 3]
running = [4, 6, 11, 12, 15]
def range_sum(left, right):
return running[right] - running[left - 1]
What does range_sum(0, 2) return?
Choose one answer, then check.
Now use the rule yourself.
orders = [4, 2, 5, 1, 3] has prefix = [0, 4, 6, 11, 12, 15]. Use one subtraction of two prefix entries to find the total of days 2 to 4 (positions 2, 3 and 4). Type the total.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Here is the whole pattern on one card:
Any question about the total of a stretch is now one subtraction, even inside another loop. The largest total over any 2 neighboring days, for example, checks 4 stretches with one subtraction each.
Write best_stretch(orders, k), which returns the largest total of any k neighboring days. k is between 1 and len(orders). Build the prefix sums first, then get each stretch's total with one subtraction. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.Keeping the notebook between calls
The dashboard's questions arrive one at a time, long after the list was loaded. Where does prefix live between them? The first problem asks exactly this, and it wants the answers from a class: a bundle of a notebook and the functions that use it. A function that lives inside a class is a method (module 0 showed one in LeetCode's class Solution). Three rules cover what you need:
- Calling the class like a function, as in
SlowSums(nums)below, makes a new object and runs its__init__method once.__init__is the constructor. - Every method receives the object as its first parameter,
self. You writesums.sum_range(1, 3), and Python passessumsasself, then 1 and 3. - A name stored on
self, such asself.nums, belongs to that one object and stays there from one call to the next.
The trace runs the plain version: it keeps the list and adds up the slice on every call. Before you step through, guess what the two calls print.
class SlowSums:def __init__(self, nums):self.nums = numsdef sum_range(self, left, right):return sum(self.nums[left:right + 1])sums = SlowSums([4, 2, 5, 1, 3])print(sums.sum_range(1, 3))print(sums.sum_range(4, 4))
(nothing printed yet)This class is correct, and it is the brute force. Each call adds up as many as n items, so q calls cost O(n · q), where q is the number of calls. Your job in the problem is to move the adding into the constructor.
The constructor is the one walk, and every call after it is two lookups and a subtraction. The prefix list costs O(n) to build and O(1) per call: O(n + q) in total, against O(n · q) for the slow class.
Counting runs that add up to k
A harder question: given a target number k, how many runs of neighboring items add up to exactly k? Such a run is called a subarray: one or more items that sit next to each other, like nums[1:4]. The numbers can be negative.
The brute force (the plain approach that tries every possibility) fixes each start, then walks right from it, adding one item at a time to a running sum and counting every end where the sum is k. A list of n items has n(n + 1)/2 subarrays (10 for 4 items), and each one costs one addition, so the brute force is O(n2) time.
Prefix sums turn each subarray into a pair of running totals. Take [2, -1, 1, 2] and k = 2, and write the running totals with the empty prefix in front, the way prefix is built:
| prefix | nothing | [2] | [2, -1] | [2, -1, 1] | [2, -1, 1, 2] |
|---|---|---|---|---|---|
| running total | 0 | 2 | 1 | 2 | 4 |
The subarray [-1, 1, 2] is the whole list without its first item, so its sum is 4 − 2 = 2: the running total at its end minus the running total just before its start.
In general, the subarray from position i to position j adds up to prefix[j + 1] - prefix[i]. Now walk left to right with a running total. When the walk reaches position j and adds its item, total is prefix[j + 1]. So the subarray adds up to k when total - prefix[i] is k, which is the same as prefix[i] being total - k. In words: a subarray that ends here adds up to k exactly when the running total just before its start is total - k.
So each step asks one question: how many earlier running totals equal total - k? You have answered this shape before. In the counting lesson, count_pairs walked a list with a dict that counted each number passed. At each number it added the count of its partner, target - x, and only then counted the number itself.
Here the partner is total - k, and the notebook is again a dict that counts: prefix_counts maps each running total to how many times it has appeared. A reminder: prefix_counts.get(key, 0) reads the count stored for key, or 0 when the key is missing.
Before you step through, check the 10 subarrays of [2, -1, 1, 2] by hand and count those that add up to 2.
def subarray_sum(nums, k):prefix_counts = {0: 1}total = 0count = 0for x in nums:total += xcount += prefix_counts.get(total - k, 0)prefix_counts[total] = prefix_counts.get(total, 0) + 1return count
(nothing printed yet)Count, do not only remember. On the last pass, the total 2 had appeared twice, as the table shows: after [2] and after [2, -1, 1]. Each earlier copy marks a different start, so they are two subarrays, [-1, 1, 2] and the last [2]. A set of totals would have found 2 once and counted only one of them.
The dict starts as {0: 1} for the empty prefix. A subarray that starts at position 0 has nothing before it, so the total before its start is 0. Without that row, every subarray that starts at position 0 is missed.
Someone starts the dict empty instead of with {0: 1}:
def subarray_sum(nums, k):
prefix_counts = {}
total = 0
count = 0
for x in nums:
total += x
count += prefix_counts.get(total - k, 0)
prefix_counts[total] = prefix_counts.get(total, 0) + 1
return count
What does subarray_sum([2, -1, 1, 2], 2) return? (The right answer is 4.)
Choose one answer, then check.
Trace the dict by hand once on a list with zeros, where totals repeat.
On paper, run the subarray count on nums = [0, 2, 0] with k = 2. Write a row per item: x, total, the key you look up (total - 2), what you find, count, and the dict after recording. Reveal one step at a time to check.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Recap. A subarray's sum is the running total at its end minus the running total before its start. At each item, one dict lookup counts every earlier total that is exactly k below the current one, which is every matching subarray that ends here.
Now write it from a blank function.
One walk, one lookup and one update per item: O(n) time and O(n) extra space. A sliding window (module 4: a stretch whose two ends move right) can count these in O(1) extra space when every number is positive. Negative numbers break windows, because a sum can go back down. Prefix sums do not care about signs.
Everything except one item
Last question: for every position i, the product of every item except nums[i]. For [4, 2, 3, 5] the answer is [30, 60, 40, 24]. Position 0 gets 2 × 3 × 5 = 30.
The shortcut is to multiply everything and divide by nums[i]. A single 0 breaks it. In [3, 0, 2] the product of everything is 0. The answer at position 1, where the 0 sits, is 3 × 2 = 6, but the shortcut computes 0 ÷ 0, which is an error. Once the 0 is multiplied in, the 3 and the 2 are lost. The problem rules division out.
Split "everything except i" in two: the items before i and the items after i. The prefix product before[i] is the product of the items left of i. The suffix product after[i] is the product of the items right of i; a suffix is a run that ends at the last item. A product of nothing is 1, the way a sum of nothing is 0, so before[0] and after[n - 1] are both 1.
Each comes from one walk, the prefix sum walk with multiplication. before[i] is before[i - 1] times the item just left of i, so that walk runs from the left. after[i] is after[i + 1] times the item just right of i, so that walk runs from the right: each entry needs its right neighbor filled first.
range(n - 2, -1, -1) counts down from n − 2 to 0. The third number is the step, and the stop, −1, is left out like every stop. It starts at n − 2 because after[n - 1] is already 1. Before you step through, guess after[0].
def product_except_self(nums):n = len(nums)before = [1] * nfor i in range(1, n):before[i] = before[i - 1] * nums[i - 1]after = [1] * nfor i in range(n - 2, -1, -1):after[i] = after[i + 1] * nums[i + 1]out = []for i in range(n):out.append(before[i] * after[i])return out
(nothing printed yet)Walking from the right is the move to practice, so put one together yourself. The same shape with sums gives suffix sums, with one difference: here suffix[i] includes nums[i], and the list is one longer than nums, with a 0 at the end for the empty suffix, the way prefix has a 0 at the front.
Put the lines in order to build suffix_sums(nums). It returns a list one longer than nums where suffix[i] is the sum of nums[i] through the last item, and suffix[n] is 0, the sum of nothing. The walk runs from the right. Two lines do not belong.
Add lines from the list below, in order.
def suffix_sums(nums):return suffixsuffix[i] = suffix[i + 1] + nums[i]suffix = [0] * (n + 1)suffix[i] = suffix[i - 1] + nums[i]n = len(nums)for i in range(n - 1, 0, -1):for i in range(n - 1, -1, -1):
The two lists can go. Write the left products straight into the answer list, then walk from the right keeping the product of the right side in one number. That brings the extra space down to O(1), not counting the answer. The problem's hints lead you there.
In the one-number version, order inside the second walk matters: multiply out[i] by after first, then multiply after by nums[i]. The other order would multiply each item into its own answer.
Last, say the subarray count out loud, the way you would before typing it.
Explain, as you would to an interviewer before typing, how you would count the subarrays that add up to k. Name the brute force and its cost, then give the walk, the notebook, the promise and the cost of the prefix sum version, and say why the dict starts with {0: 1}.
Saved in this browser as you type.