FrontEndCollection
FrontEndCollection copied to clipboard
Product of Array Except Self
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]
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]
It looks like we fliped the array, because we traverse from the back but get the result on the first index
- Traverse from right to left and we got... [24, 12, 4, 1]
- Traverse from the left to right, finally we got... [24, 12, 8, 6] leftMult was [1, 1, 2, 6]
var productExceptSelf = function(nums) {
const res = [];
let leftMult = 1;
let rightMult = 1;
for(let i = nums.length - 1; i >= 0; i--) {
res[i] = rightMult;
rightMult *= nums[i];
}
for(let i = 0; i < nums.length; i++) {
res[i] *= leftMult;
leftMult *= nums[i];
}
return res;
};