DSA Visualizer · 25 visualizationsProduct of Array Except Self
Product of Array Except Self
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i]. You must solve it without division and in O(n).
Start every answer at 1 — it will accumulate the prefix product, then the suffix product.
Problem
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i]. You must solve it without division and in O(n) time.
Examples
Constraints
- 2 ≤ nums.length ≤ 10⁵
- -30 ≤ nums[i] ≤ 30
- The product of any prefix or suffix fits in a 32-bit integer
Intuition
answer[i] is exactly (product of everything left of i) × (product of everything right of i). Compute the prefix products in one left-to-right pass, storing them directly into the answer array, then multiply in the suffix products with one right-to-left pass — no division needed, and no extra array beyond the output.
Brute force → Optimal
For each index, multiply every other element by looping over the whole array again.
One pass fills answer[i] with the prefix product (everything before i). A second pass, right to left, multiplies in the suffix product (everything after i) using a single running variable.
Complexity
Edge cases
- Exactly one zero in the array: every answer is 0 except at the zero's own index, which gets the product of everything else.
- Two or more zeros: every answer is 0, since every index excludes at most one zero.
Common mistakes
- Dividing by nums[i] from the total product — breaks the moment any element is 0, and the problem explicitly disallows division anyway.
- Allocating a separate prefix array and a separate suffix array instead of reusing the output array and one running variable for the suffix pass.