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
Hello @chygoz2, thank you for participating in Week 4 of Algorithm Fridays.
This is a robust and decent solution - use of two pointers, the check on line 9, the check for each entry of the array, the use of
map
function.However, the one test your solution fails is when one of the entries in the array is 0. For example:
What do you think?