Created
March 19, 2018 03:08
-
-
Save naveedn/00955f4928c1e3d3177eff40967b2fa1 to your computer and use it in GitHub Desktop.
Medium Article Snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Algorithmic Complexity:
O(3n) speed
O(2n) space
Previous Approach: https://gist.github.com/naveedn/b16bd0a15ba089c58187eeacf4448efa
Next Approach: https://gist.github.com/naveedn/c54b39521c0b07b0f9bde8ec020eda9d