Created
April 15, 2020 16:24
-
-
Save mrboli/cb2faeef1d2d9a17c6ca129c554c8437 to your computer and use it in GitHub Desktop.
Product of Array Except Self
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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