LeetCode #238 Medium

Product of Array Except Self

Product of Array Except Self is LeetCode 238 (Medium). Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i].

  • You must not use division, and the solution must run in O(n) time.
  • nums has up to 10⁵ values between −30 and 30, and every answer fits in a 32-bit integer.
  • Follow-up: use O(1) extra space; the output array does not count.
Constraints
  • 2 <= nums.length <= 10⁵
  • -30 <= nums[i] <= 30
  • The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.
arrayprefix-productsuffix-product
Open on LeetCode ↗
02

Intuition

Everything except position i splits into two parts: the numbers to its left and the numbers to its right. So answer[i] is the product of the left part times the product of the right part.

Both parts can be built as running products. Walking left to right, one running product holds everything before i; walking right to left, another holds everything after i. Each step costs one multiplication, nothing is recomputed, and no division is needed.

An empty part (nothing left of index 0, nothing right of the last index) has product 1, which is why both running products start at 1.

How to spot this pattern

When every output combines all elements except the current one, split it into a part before and a part after. Running products or sums from both ends give each part in one pass. Trapping Rain Water (42) and Candy (135) use the same left pass plus right pass idea.

03

Approach

Try it first

Before reading on: for [1, 2, 3, 4], write the product of everything left of each index, then everything right of it. How do the two lists give the answer? Aim for O(n) time without division.

1

Fill in the left products

Set prefix = 1. For i from left to right, write answer[i] = prefix, then multiply prefix by nums[i]. Writing first keeps nums[i] out of its own answer, so after this pass answer[i] holds the product of everything left of i.

2

Multiply in the right products

Set suffix = 1. For i from right to left, multiply answer[i] by suffix, then multiply suffix by nums[i]. Now answer[i] is left part × right part. The right side lives in one variable instead of a second array, which meets the O(1)-space follow-up.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def productExceptSelf(self, nums: List[int]) -> List[int]:
▶3 answer = [1] * len(nums)
▶4 prefix = 1
▶5 for i in range(len(nums)):
▶6 answer[i] = prefix
▶7 prefix *= nums[i]
▶8 
▶9 suffix = 1
▶10 for i in range(len(nums) - 1, -1, -1):
▶11 answer[i] *= suffix
▶12 suffix *= nums[i]
▶13 return answer
numsanswer011121231341prefix1answer = all 1s, prefix = 1
prefix1product of nothing yet
answer starts as all 1s and prefix starts at 1, the product of an empty list. Starting at 0 would make every answer 0.
numsanswer011121231341nothing to the leftprefix1→1after × 1answer[0] = 1, then prefix = 1
i0
answer[0]1product left of 0
prefix1now includes nums[0]
Nothing is left of index 0, so answer[0] gets the empty product 1. Only after writing, multiply prefix by nums[0] = 1, giving 1, so that nums[0] never lands in its own answer.
numsanswer011121231341left part = 1prefix1→2after × 2answer[1] = 1, then prefix = 2
i1
answer[1]1product left of 1
prefix2now includes nums[1]
Everything left of index 1 is 1 = 1, and prefix already holds exactly that, so write it into answer[1]. Only after writing, multiply prefix by nums[1] = 2, giving 2, so that nums[1] never lands in its own answer.
numsanswer011121232341left part = 2prefix2→6after × 3answer[2] = 2, then prefix = 6
i2
answer[2]2product left of 2
prefix6now includes nums[2]
Everything left of index 2 is 1 × 2 = 2, and prefix already holds exactly that, so write it into answer[2]. Only after writing, multiply prefix by nums[2] = 3, giving 6, so that nums[2] never lands in its own answer.
numsanswer011121232346left part = 6prefix6→24after × 4answer[3] = 6, then prefix = 24
i3
answer[3]6product left of 3
prefix24now includes nums[3]
Everything left of index 3 is 1 × 2 × 3 = 6, and prefix already holds exactly that, so write it into answer[3]. Only after writing, multiply prefix by nums[3] = 4, giving 24, so that nums[3] never lands in its own answer.
numsanswer011121232346suffix1left parts done, suffix = 1
answer[1, 1, 2, 6]left products
suffix1product of nothing yet
After the first pass each answer[i] holds the product of everything to its left. Now walk from the right with suffix = 1 and multiply in everything to the right. One variable is enough, so no second array is needed.
numsanswer011121232346nothing to the rightsuffix1→4after × 4answer[3] = 6 × 1 = 6, then suffix = 4
i3
answer[3]6left × right
suffix4now includes nums[3]
Nothing is right of the last index, so suffix is still 1 and answer[3] stays 6. Then multiply suffix by 4, giving 4.
numsanswer011121238346right part = 4suffix4→12after × 3answer[2] = 2 × 4 = 8, then suffix = 12
i2
answer[2]8left × right
suffix12now includes nums[2]
Everything right of index 2 is 4 = 4. Multiply it into answer[2]: 2 × 4 = 8, the left part times the right part. Then multiply suffix by 3, giving 12.
numsanswer0111212238346right part = 12suffix12→24after × 2answer[1] = 1 × 12 = 12, then suffix = 24
i1
answer[1]12left × right
suffix24now includes nums[1]
Everything right of index 1 is 3 × 4 = 12. Multiply it into answer[1]: 1 × 12 = 12, the left part times the right part. Then multiply suffix by 2, giving 24.
numsanswer01241212238346right part = 24suffix24→24after × 1answer[0] = 1 × 24 = 24, then suffix = 24
i0
answer[0]24left × right
suffix24now includes nums[0]
Everything right of index 0 is 2 × 3 × 4 = 24. Multiply it into answer[0]: 1 × 24 = 24, the left part times the right part. Then multiply suffix by 1, giving 24.
numsanswer01241212238346suffix24return [24, 12, 8, 6]
answer[24, 12, 8, 6]no division used
Done. Every answer[i] is the product of the left part and the right part, which is every value except nums[i]. Two passes of 4 steps, and the only extra memory was prefix and suffix.
05

Prefix and suffix product arrays

left[i] is the product of everything before i, built from left to right; right[i] is the product of everything after i, built from right to left. Multiplying the two arrays element by element gives the answer.

▶1class Solution:
▶2 def productExceptSelf(self, nums: List[int]) -> List[int]:
▶3 n = len(nums)
▶4 left = [1] * n
▶5 right = [1] * n
▶6 for i in range(1, n):
▶7 left[i] = left[i - 1] * nums[i - 1]
▶8 for i in range(n - 2, -1, -1):
▶9 right[i] = right[i + 1] * nums[i + 1]
▶10 return [left[i] * right[i] for i in range(n)]
06

Common pitfalls

Multiplying nums[i] in before writing

✗ Wrong
prefix *= nums[i]
answer[i] = prefix
✓ Right
answer[i] = prefix
prefix *= nums[i]

Updating first puts nums[i] into its own answer: for [1, 2, 3, 4] the first pass would write [1, 2, 6, 24] instead of [1, 1, 2, 6]. The right-to-left pass needs the same order with suffix.

07

Edge cases

Zeros in nums

In [-1, 1, 0, -3, 3] every index except the zero's has the 0 on its left or right, so it gets 0, and the zero's own index gets the product of the rest, 9. With two zeros every answer is 0. The same two passes do this with no special branch.

08

Complexity

Time
O(n)
Space
O(1) extra
The code makes two passes of n steps each. Apart from the returned answer, which the problem does not count, the code keeps only prefix and suffix.
09

Product of Array Except Self FAQ

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

The problem forbids division, and it also breaks on zeros: dividing by 0 fails, so you would need separate cases for no zeros, one zero and two or more zeros. The two-pass method above handles all three with the same two passes.