238. Product of Array Except Self
Asked at 30Amazon68Apple67Microsoft64Bloomberg60Meta54Google53Asana95ThousandEyes100ZS Associates100FreshWorks81PayPal74Avito74Uber72Okta71Zoho65Nvidia60Yandex57Adobe55ServiceNow55eBay53LinkedIn47tcs46Oracle45Infosys45Snap45Goldman Sachs45Walmart Labs43Visa39Salesforce35TikTok26
Problem
Return an array answer where answer[i] is the product of every element of nums except nums[i]. Do it in O(n) without using division.
Example: [1,2,3,4] → [24,12,8,6]
Constraints: 2 ≤ n ≤ 10⁵; every prefix/suffix product fits in a 32-bit int. Follow-up: O(1) extra space (the output doesn't count).
ans[i] = (product of everything left of i) × (product of everything right of i). Fill left products in one pass, then multiply by a running right product in a reverse pass. No division needed.
nums [ 1, 2, 3, 4]
left [ 1, 1, 2, 6] (product before i)
right [24, 12, 4, 1] (product after i)
answer [24, 12, 8, 6]
Complexity: O(n) time, O(1) extra space (output excluded).
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [1] * n
for i in range(1, n):
ans[i] = ans[i - 1] * nums[i - 1]
right = 1
for i in range(n - 1, -1, -1):
ans[i] *= right
right *= nums[i]
return ans
assert Solution().productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6]
assert Solution().productExceptSelf([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0]
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
ans[0] = 1;
for (int i = 1; i < n; i++) ans[i] = ans[i - 1] * nums[i - 1];
int right = 1;
for (int i = n - 1; i >= 0; i--) {
ans[i] *= right;
right *= nums[i];
}
return ans;
}
}
func productExceptSelf(nums []int) []int {
n := len(nums)
ans := make([]int, n)
ans[0] = 1
for i := 1; i < n; i++ {
ans[i] = ans[i-1] * nums[i-1] // product of everything to the left
}
right := 1
for i := n - 1; i >= 0; i-- {
ans[i] *= right
right *= nums[i]
}
return ans
}