Created
August 31, 2017 16:39
-
-
Save jykim16/7cceee093fb05b7226a1c9d68fa5bd7f 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
var productExceptSelf = function(nums) { | |
let zeroCount = 0; | |
let productWithoutZero = 1; | |
let product = nums.reduce((accum, num)=>{ | |
if(num === 0) {zeroCount++} | |
if(num !== 0) {productWithoutZero *= num} | |
return accum * num; | |
}, 1); | |
return nums.map((num, i)=>{ | |
if(zeroCount === 0) { | |
return product/num; | |
} else if (zeroCount === 1) { | |
if(num===0) { | |
return productWithoutZero; | |
} else { | |
return product; | |
} | |
} else { | |
return 0; | |
} | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment