Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created January 15, 2026 11:23
Show Gist options
  • Select an option

  • Save mustafadalga/88985dce56da218759019a7b168dde73 to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/88985dce56da218759019a7b168dde73 to your computer and use it in GitHub Desktop.
Compute array of products excluding self (without division) in O(n) time. Efficient two-pass solution using prefix and suffix products; handles zeros and negatives; no division used.
// resource of question: https://www.greatfrontend.com/questions/algo/array-product-excluding-current
export default function arrayProductExcludingCurrent(numbers: number[]): number[] {
const result: number[] = []
for (let index = numbers.length - 1; index >= 0; index--) {
result[index] = index === numbers.length - 1 ? 1 : numbers[index + 1] * result[index + 1]// suffix
}
let leftProduct = 1
for (let index = 0; index < numbers.length; index++) {
leftProduct = index === 0 ? leftProduct : leftProduct * numbers[index - 1]
result[index] = leftProduct * result[index]
}
return result
}
console.log(arrayProductExcludingCurrent([ 1, 2, 3 ]))
console.log(arrayProductExcludingCurrent([ 2, 0, 3 ]))
console.log(arrayProductExcludingCurrent([ 0, 0, -1, 1 ]))
console.log(arrayProductExcludingCurrent([ 2, 3, 3, 2, 5 ]))// [90, 60, 60, 90, 36]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment