Skip to content

Instantly share code, notes, and snippets.

@naveedn
Created March 19, 2018 03:08
Show Gist options
  • Save naveedn/00955f4928c1e3d3177eff40967b2fa1 to your computer and use it in GitHub Desktop.
Save naveedn/00955f4928c1e3d3177eff40967b2fa1 to your computer and use it in GitHub Desktop.
Medium Article Snippet
const input = [1,3,5,7];
function product(inputArr) {
const productMap = new Map();
const resultArr = [];
let product = 1;
for(let i = 0; i < inputArr.length; i++) {
product *= inputArr[i];
productMap.set(i+1, product);
}
product = 1; // reset product
for(let j = inputArr.length - 1; j >= 0; j--) {
product *= inputArr[j];
const beforeIndex = productMap.get(j-1);
if (beforeIndex) {
const finalProduct = beforeIndex * product;
productMap.set(j-1, finalProduct);
} else {
productMap.set(j-1, product);
}
}
for(let k = 0; k < inputArr.length; k++) {
resultArr.push(productMap.get(k));
}
return resultArr;
}
console.log(product(input));
@naveedn
Copy link
Author

naveedn commented Mar 19, 2018

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