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
})
}
@meekg33k
Copy link

meekg33k commented May 2, 2021

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:

arrayProduct ([4, 3, 0]); ❌ // should return [0, 0, 12] but yours returns [0, 0, NaN]

What do you think?

@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