Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created September 3, 2021 07:46
Show Gist options
  • Save misterpoloy/d0891e64f3034c47070eec6d74f22c17 to your computer and use it in GitHub Desktop.
Save misterpoloy/d0891e64f3034c47070eec6d74f22c17 to your computer and use it in GitHub Desktop.
Array of products excluding the current index
function arrayOfProducts(array) {
const resultArray = new Array(array.size)
const leftArray = new Array(array.size)
const rigthArray = new Array(array.size)
// Generate right array
let leftProduct = 1;
for (let i = 0; i < array.length; i++) {
leftArray[i] = leftProduct
leftProduct = leftProduct * array[i]
}
// Generat left array
let rightProduct = 1;
for (let i = array.length - 1; i >= 0; i--) {
rigthArray[i] = rightProduct
rightProduct = rightProduct * array[i]
}
// Multiply both arrays
for (let i = 0; i < array.length; i++) {
resultArray[i] = rigthArray[i] * leftArray[i]
}
return resultArray
}
// Do not edit the line below.
exports.arrayOfProducts = arrayOfProducts;
@misterpoloy
Copy link
Author

screenshot1

array of products

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