Product of Array Except Self
Given an array nums, return an array where each element is the product of all other elements. Do not use division.
Example: nums = [1,2,3,4] → Output: [24,12,8,6]
Sample Input
—
Sample Output
—
Constraints
- 2 <= nums.length <= 10^5
- -30 <= nums[i] <= 30
- Guaranteed product of any prefix/suffix fits in 32-bit integer
Test Cases
Case 1
Args: [[1,2,3,4]]
Expected: [24,12,8,6]
Topics
Left and Right Products
function productExceptSelf(nums) {
const n = nums.length, result = Array(n).fill(1);
let prefix = 1;
for (let i = 0; i < n; i++) { result[i] = prefix; prefix *= nums[i]; }
let suffix = 1;
for (let i = n-1; i >= 0; i--) { result[i] *= suffix; suffix *= nums[i]; }
return result;
}
Time: O(n) | Space: O(1) extra
Saved in this browser only. Private to you.