Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# Abiola-Farounbi/productOfArray.js

Created May 1, 2021
The function returns products of element in an array
 //Given an integer array nums, //write a function that returns an array products, //such that each entry at position i, in products is a product of all the other elements in nums except num[i] // #algorithm friday set4 const productOfArray = (nums) => { // testing for array or empty array if (!Array.isArray(nums) || nums.length == 0 ) return ' Invalid Input ' let count = nums.length let start = new Array(count); let end = new Array(count); let product = new Array(count); // setting the intials of the array start = 1; end[count-1] = 1 // the start array for (let i = 1; i < count; i++){ start[i] = nums[i - 1] * start[i - 1]; } // the end array for (let j = count - 2; j >= 0; j--){ end[j] = nums[j + 1] * end[j + 1]; } // the product array = start * end for (let i = 0; i < count; i++){ product[i] = start[i] * end[i]; } return product } console.log(productOfArray([4,5,10,2])) //return [ 100, 80, 40, 200 ]

### meekg33k commented May 2, 2021

 Hello @Abiola-Farounbi, thank you for participating in Week 4 of Algorithm Fridays. This is a really decent solution that passes all the test cases. Very sweet! I like your use of edge case checks on line 9. One thing to say about the checks however is that, if an empty array is passed, it's okay to return an empty array as your result instead of throwing `'Invalid Input'` errors. Also, your solution is optimal in terms of time complexity O(N). However, your solution uses three arrays `start`, `end` and the final `product`. Do you think you can come up with a better solution in terms of memory efficiency? That said, this was really good. Kudos!

### Abiola-Farounbi commented May 2, 2021

 Thanks a lot for the feedback, I have been pondering over it for some time, so far this is what I have been able to come up with, hopefully in due time, I will be able to come with a more memory efficient approach..
to join this conversation on GitHub. Already have an account? Sign in to comment