Skip to content

Instantly share code, notes, and snippets.

@mrboli
Created April 15, 2020 16:24
Show Gist options
  • Save mrboli/cb2faeef1d2d9a17c6ca129c554c8437 to your computer and use it in GitHub Desktop.
Save mrboli/cb2faeef1d2d9a17c6ca129c554c8437 to your computer and use it in GitHub Desktop.
Product of Array Except Self
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelfTwoArray = function(nums) {
const prodLeft = [];
const prodRight = [];
prodLeft[0] = 1;
prodRight[nums.length - 1] = 1;
const ans = [];
for (let i = 1; i < nums.length; i++) {
const leftIdx = i;
const rightIdx = nums.length - 1 - i;
const prevLeft = leftIdx - 1;
const prevRight = rightIdx + 1;
prodLeft[leftIdx] = nums[prevLeft] * prodLeft[prevLeft];
prodRight[rightIdx] = nums[prevRight] * prodRight[prevRight];
}
for (let i = 0; i < nums.length; i++) {
ans[i] = prodLeft[i] * prodRight[i];
}
return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment