Last active
March 19, 2018 04:19
-
-
Save naveedn/c54b39521c0b07b0f9bde8ec020eda9d 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 resultArr = new Array(inputArr.length); | |
let product = 1; | |
for(let i = 0; i < inputArr.length; i++) { | |
product *= inputArr[i]; | |
if (i+1 < inputArr.length) { | |
resultArr[i+1] = product; | |
} | |
} | |
product = 1; // reset product | |
for(let j = inputArr.length - 1; j >= 0; j--) { | |
product *= inputArr[j]; | |
if (j-1 >= 0) { | |
resultArr[j-1] *= product; | |
} else { | |
resultArr[0] = product; | |
} | |
} | |
return resultArr; | |
} | |
console.log(product(input)); |
One of the underlying "hacks" that allows us to optimize this function is the fact that multiplication is associative:
( a × b ) × c = a × ( b × c ))
Because we don't care the order in which we multiply the values together, we can speed things up if we create a product of the values before an index, and multiply that with the product of values after an index. No matter what, it will still yield the proper result.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Algorithmic Complexity:
Speed: O(2n)
Space: O(n)
Previous Approach: https://gist.github.com/naveedn/00955f4928c1e3d3177eff40967b2fa1