Product of Array Except Self
Multiply everything except the number at each index, without division, using prefix and suffix products.
The problem
You get an integer array nums. Return an array answer where answer[i] is the product of every element of nums except nums[i]. You can assume every such product fits in a 32-bit integer. Solve it in O(n) time without using division.
Input nums = [2, 3, 5, 4]
Output [60, 40, 24, 30]
answer[0] = 3 * 5 * 4 = 60, answer[1] = 2 * 5 * 4 = 40, and so on.
Input nums = [4, 0, -2, 3]
Output [0, -24, 0, 0]
Every product except answer[1] includes the 0; answer[1] = 4 * (-2) * 3 = -24.
Key constraint: No division is allowed, and the answer must take O(n) time.
How to spot the pattern
- Each answer combines everything to the left of i with everything to the right of i.
- Division is not allowed, and it would break on zeros anyway, so you need another way to leave out nums[i].
The idea
The product of everything except nums[i] is the product of everything before i times the product of everything after i. One left-to-right pass can write the "before" product into answer[i], and one right-to-left pass can multiply in the "after" product using a single running variable. No division is involved, so zeros need no special handling.
Brute force: For each index, multiply all the other numbers with an inner loop, which takes O(n^2) time.
Step by step
- 1Create
answerwith the same length asnums. - 2Left to right: keep
prefix, the product of the numbers before i; store it inanswer[i], then multiplyprefixbynums[i]. - 3Right to left: keep
suffix, the product of the numbers after i; multiplyanswer[i]by it, then multiplysuffixbynums[i]. - 4Return
answer.
See the pattern move
The prefix sums pattern on a small example. Step through it, or press play.
Code
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n
prefix = 1 # product of everything before i
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
suffix = 1 # product of everything after i
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answerComplexity
Time
O(n)
Space
O(1)
Two passes over the array. Apart from the answer array, which you have to return anyway, only the two running products are stored.
Watch out for
- Dividing the total product by
nums[i]: it isn't allowed here, and it fails as soon as the array contains a 0. - Multiplying
prefixorsuffixbynums[i]before using it, which putsnums[i]into its own product. - Building full prefix and suffix arrays: correct, but it uses O(n) extra space when one running product per pass is enough.
Follow-up questions
Why not divide the total product by nums[i]?
Division is ruled out here, and zeros break it: with one 0, every answer except the one at the 0 is 0, and with two or more zeros every answer is 0. Counting zeros can patch that, but the prefix and suffix passes need no special cases.
Where else does the before-and-after trick show up?
Trapping Rain Water needs the tallest bar to the left and to the right of each position, built with the same two passes, before the two-pointer version removes even those.
In Hinglish
Har index ke liye left ka product aur right ka product alag se socho; dono ko multiply karo, division ki zaroorat hi nahi.