Visualize

Pattern visualizer

Product of Array Except Self

Dividing the total product by nums[i] breaks on zeros and is usually banned anyway. The clean decomposition: out[i] = (product of everything LEFT of i) × (product of everything RIGHT of i). Two linear passes fill both factors — first a running prefix sweeps left to right writing into out, then a running suffix sweeps right to left multiplying itself in. The displayed row IS the output array as it fills. Animated on: For nums = [1,2,3,4,5], build out where out[i] is the product of every element EXCEPT nums[i]. Division is off the table..

Prefix × suffix passes — no division

time O(n)space O(1) extrastep 1 / 13
?
[0]
?
[1]
?
[2]
?
[3]
?
[4]
line 2

out starts empty and L carries 'product of all cells left of i', seeded 1. Pass 1 writes only left-products; pass 2 will multiply in the right side.

Pseudocode
1FUNCTION productExceptSelf(nums):
2 n = the length of nums; out = an empty array of size n; L = 1 (L = product of everything to the left)
3 FOR i from 0 to n-1:
4 set out[i] to L; then multiply L by nums[i]
5 R = 1 (R = product of everything to the right)
6 FOR i from n-1 down to 0:
7 multiply out[i] by R; then multiply R by nums[i]
8 RETURN out

← / → step · space play · Home restart

Where to practice Arrays