Skip to content

Instantly share code, notes, and snippets.

@naveedn
Last active March 19, 2018 04:19
Show Gist options
  • Save naveedn/c54b39521c0b07b0f9bde8ec020eda9d to your computer and use it in GitHub Desktop.
Save naveedn/c54b39521c0b07b0f9bde8ec020eda9d to your computer and use it in GitHub Desktop.
Medium Article Snippet
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));
@naveedn
Copy link
Author

naveedn commented Mar 19, 2018

Algorithmic Complexity:

Speed: O(2n)
Space: O(n)

Previous Approach: https://gist.github.com/naveedn/00955f4928c1e3d3177eff40967b2fa1

@naveedn
Copy link
Author

naveedn commented Mar 19, 2018

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