Skip to content

Instantly share code, notes, and snippets.

@lizadaly
Created August 18, 2016 21:30
Show Gist options
  • Save lizadaly/29882ab3c87e64cec8caede22d93608e to your computer and use it in GitHub Desktop.
Save lizadaly/29882ab3c87e64cec8caede22d93608e to your computer and use it in GitHub Desktop.
Find products without division, but still O(n)
/* Version without division */
var findProductsNoDiv = function (arr) {
let forw = new Array(arr.length)
let back = new Array(arr.length)
let res = new Array(arr.length)
let prod = 1
/* Go through the array forward and multiply as we go */
for (var i=0;i<arr.length;i++) {
forw[i] = prod
prod *= arr[i]
}
/* Now backwards */
prod = 1
for (var i=arr.length-1;i>=0;i--) {
back[i] = prod
prod *= arr[i]
}
/* Multiply the two arrays */
for (var i=0;i<arr.length;i++) {
res[i] = forw[i] * back[i]
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment