Skip to content

Instantly share code, notes, and snippets.

@chygoz2
Last active May 2, 2021 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chygoz2/c1dc538c2e69bab25211e939ceaba1f4 to your computer and use it in GitHub Desktop.
Save chygoz2/c1dc538c2e69bab25211e939ceaba1f4 to your computer and use it in GitHub Desktop.
Algorithm challenge week 4 solution
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
})
}
@chygoz2
Copy link
Author

chygoz2 commented May 2, 2021

@meekg33k I missed that edge case. I've now updated the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment