Created
January 15, 2026 11:23
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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