Product Of Array Except Self Problem
Description
LeetCode Problem 238.
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs inO(n)time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints:
- 2 <= nums.length <= 10^5
- -30 <= nums[i] <= 30
- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Solution
Approach: Prefix and Suffix Products
Without division, we can't take the product of the whole array and divide out nums[i]. Instead, split the answer in two: answer[i] is (the product of everything left of i) times (the product of everything right of i).
- Walk left to right with a running
leftProduct, starting at 1. At each index, first storeleftProductintoanswer[i], then multiplynums[i]into it. Soanswer[i]gets the product ofnums[0..i-1]. - Walk right to left with a running
rightProduct, also starting at 1. At each index, multiplyanswer[i]byrightProduct, then multiplynums[i]into it.
The order inside each loop matters: use the running product before including nums[i], otherwise nums[i] ends up in its own answer.
For nums = [1,2,3,4], the first pass gives [1,1,2,6] and the right-hand products are [24,12,4,1], so the answer is [24,12,8,6].
Zeros need no special case: they simply flow into the running products.
Complexity: O(n) time, where n is the length of nums. O(1) extra space besides the output array.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n
# First pass: answer[i] = product of everything to the left of i.
left_product = 1
for i in range(n):
answer[i] = left_product
left_product *= nums[i]
# Second pass: multiply in the product of everything to the right of i.
right_product = 1
for i in range(n - 1, -1, -1):
answer[i] *= right_product
right_product *= nums[i]
return answer