iq.lab
Python starts when a code cell comes near or you run one
03 Arrays and hash maps

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.

About 1 hour 45 minutes, with the 3 problems worked in it
By the end you can
  • 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.

Step throughBuilding the prefix sums
Step 1 of 21
Line 1 is about to run.
orders = [4, 2, 5, 1, 3]
prefix = [0]
total = 0
for x in orders:
total += x
prefix.append(total)
print(prefix)
Names
no names yet
Output
(nothing printed yet)

Read the result as a table. Each entry is the sum of the days before its position:

i012345
prefix[i]046111215
adds upnothingday 0days 0 to 1days 0 to 2days 0 to 3days 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.

PredictBuild it by hand

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.

Step throughThree range sums, one subtraction each
Step 1 of 13
Line 1 is about to run.
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 + 1
print(prefix[end] - prefix[left])
Names
no names yet
Output
(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:

Quick checkThe missing 0

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.

Work it outOne subtraction

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.

total of days 2 to 4

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.

Code itThe best stretch of k days

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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 write sums.sum_range(1, 3), and Python passes sums as self, then 1 and 3.
  • A name stored on self, such as self.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.

Step throughA class keeps its notebook between calls
Step 1 of 15
Line 1 is about to run.
class SlowSums:
def __init__(self, nums):
self.nums = nums
def 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))
Names
no names yet
Output
(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.

easyPrefix sumsDesign as coding target 15 min

Range sum query

You get a list of integers nums that never changes, followed by many questions about it. Each question gives two positions, left and right, and wants the total of the items from position left through position right, both ends included.

Write a class NumArray. Its constructor (the __init__ method, which runs once when you write NumArray(nums)) receives the list. Its method sum_range(left, right) answers one question by returning that total. One object can get up to 100,000 questions, so the work per question has to be small. (LeetCode spells the method sumRange.)

Example 1
InputNumArray([3, -1, 4, 2, 5]), then sum_range(0, 2), sum_range(1, 3), sum_range(4, 4)Output6, 5, 5

3 + (-1) + 4 = 6, then (-1) + 4 + 2 = 5, then the single item at position 4, which is 5.

Example 2
InputNumArray([4, -2, 1, 0, 6]), then sum_range(0, 4), sum_range(1, 2), sum_range(3, 3)Output9, -1, 0

The whole list adds up to 9. Positions 1 and 2 give -2 + 1 = -1. Position 3 alone gives 0: a range can be one item.

Constraints
  • 1 ≤ len(nums) ≤ 105

  • -105 ≤ nums[i] ≤ 105

  • 0 ≤ left ≤ right < len(nums)

  • Up to 105 calls to sum_range on one object.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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:

prefixnothing[2][2, -1][2, -1, 1][2, -1, 1, 2]
running total02124

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.

Step throughCounting runs that add up to k
Step 1 of 24
Line 1 is about to run.
def subarray_sum(nums, k):
prefix_counts = {0: 1}
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
Names
no names yet
Output
(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.

Quick checkWithout the empty prefix

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 paperTrace the dict with zeros

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.

count

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.

mediumPrefix sumsHash maps and sets target 25 min

Subarrays that sum to k

You get a list of integers nums and an integer k. A subarray is a run of one or more items that sit next to each other in the list, such as nums[1:4] (positions 1, 2 and 3). Return how many subarrays add up to exactly k.

Two subarrays count separately when they start or end at different positions, even if they hold the same values. The numbers can be negative or zero.

Example 1
Inputnums = [3, 1, 2, 4], k = 3Output2

[3] at position 0, and [1, 2] at positions 1 and 2.

Example 2
Inputnums = [1, -1, 1, -1], k = 0Output4

[1, -1] at positions 0 to 1, [-1, 1] at 1 to 2, [1, -1] at 2 to 3, and the whole list.

Constraints
  • 1 ≤ len(nums) ≤ 20,000

  • -1,000 ≤ nums[i] ≤ 1,000

  • -107 ≤ k ≤ 107

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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].

Step throughProducts before and after each position
Step 1 of 31
Line 1 is about to run.
def product_except_self(nums):
n = len(nums)
before = [1] * n
for i in range(1, n):
before[i] = before[i - 1] * nums[i - 1]
after = [1] * n
for 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
Names
no names yet
Output
(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 in orderSuffix sums, from the right

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • def suffix_sums(nums):
    • return suffix
    • suffix[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.

    mediumPrefix sums target 25 min

    Product of everything else

    You get a list of integers nums. For each position i, multiply together all the items except the one at i. Return those products as a new list out in position order, so out[i] is the product for position i. Do not change nums.

    Solve it without division. Dividing the product of the whole list by nums[i] fails as soon as the list holds a 0.

    Example 1
    Inputnums = [2, 3, 4, 5]Output[60, 40, 30, 24]

    out[0] is 3 × 4 × 5 = 60, out[1] is 2 × 4 × 5 = 40, out[2] is 2 × 3 × 5 = 30, out[3] is 2 × 3 × 4 = 24.

    Example 2
    Inputnums = [3, 0, 2, -1]Output[0, -6, 0, 0]

    Every product that includes the 0 is 0. Only out[1] leaves the 0 out: 3 × 2 × (-1) = -6.

    Constraints
    • 2 ≤ len(nums) ≤ 105

    • -30 ≤ nums[i] ≤ 30

    • The product of any prefix of nums (its first i items) or suffix (its last i items) fits in a 32-bit integer. (Python integers have no size limit; this matters in languages such as Java.)

    • No division.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay it like you would in the room

    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}.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint