Skip to content

visual walkthrough

Product of Array Except Self

MediumPrefix & Suffix ProductsReported at: AmazonMetaMicrosoft+5

Prefix/suffix passes without division; a very frequent Amazon and Meta question.

Solve on LeetCode

The idea

The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Both can be built incrementally.

Sweep left to right storing the running left product, then sweep right to left multiplying in the running right product.

Complexity

approachtimespace
Multiply the restO(n²)O(1)
Prefix and suffixO(n)O(1)

More walkthroughs