Last active
May 2, 2021 15:43
-
-
Save chygoz2/c1dc538c2e69bab25211e939ceaba1f4 to your computer and use it in GitHub Desktop.
Algorithm challenge week 4 solution
This file contains 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
const arrayProduct = nums => { | |
if(!Array.isArray(nums)) throw new Error('Invalid input') | |
let product = 1 | |
let countOfZeros = 0; | |
let productWithoutZeros = 1 | |
for (let i = 0, j = nums.length - 1; i <= j; i++, j--) { | |
if (typeof nums[i] != 'number' || typeof nums[j] != 'number') throw new Error('Invalid input') | |
if (nums[i] == 0) { | |
countOfZeros++ | |
} | |
product *= nums[i] | |
productWithoutZeros = nums[i] != 0 ? productWithoutZeros * nums[i] : productWithoutZeros | |
if (i != j) { | |
if (nums[j] == 0) { | |
countOfZeros++ | |
} | |
product *= nums[j] | |
productWithoutZeros = nums[j] != 0 ? productWithoutZeros * nums[j] : productWithoutZeros | |
} | |
} | |
return nums.map(num => { | |
return countOfZeros > 1 ? 0 : num != 0 ? product / num : productWithoutZeros | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@meekg33k I missed that edge case. I've now updated the solution.