Last active
March 19, 2018 04:05
-
-
Save naveedn/b16bd0a15ba089c58187eeacf4448efa 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 beforeMap = new Map(); | |
const afterMap = new Map(); | |
const resultArr = []; | |
let product = 1; | |
let reverseProduct = 1; | |
for(let i = 0; i < inputArr.length; i++) { | |
product *= inputArr[i]; | |
beforeMap.set(i+1, product); | |
} | |
for(let j = inputArr.length - 1; j >= 0; j--) { | |
reverseProduct *= inputArr[j]; | |
afterMap.set(j-1, reverseProduct); | |
} | |
for(let k = 0; k < inputArr.length; k++) { | |
let beforeIndex = beforeMap.get(k); | |
let afterIndex = afterMap.get(k); | |
if (beforeIndex && afterIndex) { | |
resultArr.push(beforeIndex * afterIndex); | |
} else if (beforeIndex) { | |
resultArr.push(beforeIndex); | |
} else { | |
resultArr.push(afterIndex); | |
} | |
} | |
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:
speed: O(3n)
space: O(3n)
Previous Approach: https://gist.github.com/naveedn/93b7eaa01da0dbc9d3a1e7e45894cf15
Next Approach: https://gist.github.com/naveedn/00955f4928c1e3d3177eff40967b2fa1