Skip to content
BytePatterns

Product Except Self

Arrays: lesson 12 of 14

Two sweeps beat one division.

Lesson 12 of 14 · 5 min

Product Except Self

Step 1 of 10

Every answer is everything left of i times everything right of i. Two sweeps, no division.

The Idea

The answer at index i is everything to its left multiplied by everything to its right. So make two sweeps. Going left to right, write the running product of the left side into the output, before folding the current value in. Then sweep back, multiplying in the running product of the right side. Each cell meets both halves of the array without ever meeting itself.

Real-World Example

A production line reports the yield of each stage, and management wants, per stage, the combined yield of all the others — the number that says what the line would do if that stage were perfect. One walk down the line and one walk back gives every stage its figure.

The Code

def product_except_self(nums):
    out = [1] * len(nums)
    prefix = 1
    for i in range(len(nums)):              # everything left of i
        out[i] = prefix
        prefix *= nums[i]
    suffix = 1
    for i in range(len(nums) - 1, -1, -1):  # fold in everything right of i
        out[i] *= suffix
        suffix *= nums[i]
    return out

print(product_except_self([2, 3, 4, 5]))   # [60, 40, 30, 24]

Python

Your turn

What does this print?

nums = [1, 2, 3]
out = [1, 1, 1]
p = 1
for i in range(3):
  out[i] = p
  p *= nums[i]
print(out)

Mini quiz

1 / 3

Why not divide the total product by nums[i]?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.