Skip to content

Instantly share code, notes, and snippets.

@revanth0212
Created April 21, 2018 19:48
Show Gist options
  • Select an option

  • Save revanth0212/c8a761a3cd8476fa412901a4ad100581 to your computer and use it in GitHub Desktop.

Select an option

Save revanth0212/c8a761a3cd8476fa412901a4ad100581 to your computer and use it in GitHub Desktop.
Find product of all the elements in the array except self. (without division)
var leftArray = rightArray = prod = []
var leftHashMap = rightHashMap = {}
function constructLeftArrayElement (arr, i) {
if (i <= 0) {
leftHashMap[i] = 1
return 1
} else {
if (leftHashMap.hasOwnProperty(i-1)) {
var val = leftHashMap[i-1] * arr[i-1]
leftHashMap[i] = val
return val
} else {
var val = constructLeftArrayElement(arr, i-1) * arr[i-1]
leftHashMap[i] = val
return val
}
}
}
function constructRightArrayElement (arr, i) {
if (i >= arr.length-1) {
rightHashMap[i] = 1
return 1
} else {
if (rightHashMap.hasOwnProperty(i+1)) {
var val = rightHashMap[i+1] * arr[i+1]
rightHashMap[i] = val
return val
} else {
var val = constructRightArrayElement(arr, i+1) * arr[i+1]
rightHashMap[i] = val
return val
}
}
}
var productExceptSelf = function(nums) {
var leftArray = []
var rightArray = []
var prod = []
leftHashMap = {}
rightHashMap = {}
var i = 0
for(i = 0; i < nums.length; i++) {
leftArray[i] = constructLeftArrayElement(nums, i)
}
for(i = 0; i < nums.length; i++) {
rightArray[i] = constructRightArrayElement(nums, i)
}
for(i = 0; i < nums.length; i++) {
prod[i] = leftArray[i] * rightArray[i]
}
return prod
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment