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 ]
@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