Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 238 Product of Array Except Self - Space Optimization

One output array

The O(1)O(1) extra space solution uses the output array for prefix products, then multiplies in suffix products in a second pass. First pass: answer[i]=answer[i] = product of all elements before ii.

Start with answer[0]=1answer[0] = 1, then answer[i]=answer[i1]×nums[i1]answer[i] = answer[i-1] \times nums[i-1]. Second pass: track suffixsuffix (product of elements after current index). For each ii from n1n-1 down to 00: answer[i]=answer[i]×suffixanswer[i] = answer[i] \times suffix, then suffix=suffix×nums[i]suffix = suffix \times nums[i]. After both passes, answer[i]answer[i] = product of all elements except nums[i]nums[i]. Time: O(n)O(n), Space: O(1)O(1) excluding output.