Problem Statement

Product of Array Except Self

You are given a list of numbers called nums. You need to build a new list called answer. For each spot, answer[i] should be the result of multiplying together every number in the list except the one sitting at spot i. Two extra rules make this tricky: your solution must run in O(n) time, which means roughly one quick pass over the list, and you are not allowed to use division.

mediumArrayArrays & HashingTime: O(n) · Space: O(1)

Signals to notice

product of all elements except currentno division allowedprefix and suffix

Brute force first

For each element, multiply all others. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Two passes: left-to-right prefix products, then right-to-left suffix products. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on nums=[1,2,3,4]

init: result=[1,1,1,1], prefix=1
prefix pass i=0..3: write prefix into result[i], then prefix*=nums[i] -> result=[1,1,2,6], prefix=24
suffix=1, walk right-to-left
i=3: result[3]=6*1=6, suffix=1*4=4
i=2: result[2]=2*4=8, suffix=4*3=12
i=1: result[1]=1*12=12, suffix=12*2=24
i=0: result[0]=1*24=24, suffix=24
return [24,12,8,6]

What must stay true

result[i] = product of all elements to the left × product of all elements to the right. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

result = array of 1s, length n
prefix = 1
for i from 0 to n-1: result[i] = prefix; prefix *= nums[i]
suffix = 1
for i from n-1 down to 0: result[i] *= suffix; suffix *= nums[i]
return result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Trying to use division — the problem explicitly forbids it, and zeros break division anyway. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Arrays & Hashing Pattern