Skip to content

Instantly share code, notes, and snippets.

@Abiola-Farounbi
Created May 1, 2021 21:08
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 Abiola-Farounbi/3ad0ef587d3c65c584fe2ff1ea6bb5ae to your computer and use it in GitHub Desktop.
Save Abiola-Farounbi/3ad0ef587d3c65c584fe2ff1ea6bb5ae to your computer and use it in GitHub Desktop.
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[0] = 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
Copy link

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
Copy link
Author

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..

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