Product of Array Except Self
Examples
Example 1:
Input: nums = [1,2,4,6]
Output: [48,24,12,8]
Example 2:
Input: nums = [-1,0,1,2,3]
Output: [0,-6,0,0,0]
Example 1:
Input: nums = [1,2,4,6]
Output: [48,24,12,8]
Example 2:
Input: nums = [-1,0,1,2,3]
Output: [0,-6,0,0,0]
Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].
Each product is guaranteed to fit in a 32-bit integer.
Follow-up: Could you solve it in time without using the division operation?
2 <= nums.length <= 1000-20 <= nums[i] <= 20Build the result using prefix and suffix products. First, set output[i] to the product of all elements before i by sweeping left to right. Then sweep right to left with a running suffix product and multiply it into output[i]. This handles zeros naturally because every position excludes itself without division.
For each index i), the product of all elements except nums[i]equals (product of elements beforei) * (product of elements after i`). The two passes compute exactly these two components for every index, so the final product is correct.
O(n)O(1) extra (excluding the output array)class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
output = [1] * n
prefix = 1
for i in range(n):
output[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
output[i] *= suffix
suffix *= nums[i]
return output