Medium General

Product of Array Except Self

Receives an array of integers and returns a new array of the same length where every position holds the product of all the other elements — never its own. It avoids division entirely (so a zero anywhere in the input needs no special case) by building two auxiliary arrays: a left-to-right pass fills prefix[i] with the product of everything strictly left of i, and a right-to-left pass fills suffix[i] with the product of everything strictly right of i, both seeded with 1 because the empty product is 1. A final pass multiplies the two per index, since everything except element i is exactly everything to its left times everything to its right. It runs in linear time; the caller's array is never mutated, an empty input returns an empty array, and a single element returns [1].

Visualization

Input

Algorithm code

Custom input

Saved inputs

References