Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Save thmain/4d41693346c859fd60b108824680cfe9 to your computer and use it in GitHub Desktop.
Save thmain/4d41693346c859fd60b108824680cfe9 to your computer and use it in GitHub Desktop.
function productPuzzle(data) {
var len = data.length
var left = new Array(len)
var right = new Array(len)
// prepare the left array
left[0] = 1
for(let i = 1; i < len; i++)
left[i] = left[i-1] * data[i-1]
console.log(left) // [ 1, 1, 2, 6 ]
// prepare the right array
right[len-1] = 1
for (let j = len-2; j >= 0; j-- )
right[j] = right[j+1] * data[j+1]
console.log(right) // [ 24, 12, 4, 1 ]
return data.map((el, index) => {
return left[index] * right[index]
})
}
console.log(productPuzzle([1, 2, 3, 4])) // [ 24, 12, 8, 6 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment