← Back to DSA Animator
Product of Array Except Self LC #238 Medium Array
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 write an algorithm that runs in O(n) time and without using the division operation.

Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Explanation: 24=2×3×4, 12=1×3×4, 8=1×2×4, 6=1×2×3
Example 2
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints: 2 ≤ nums.length ≤ 105; -30 ≤ nums[i] ≤ 30; The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. O(1) extra space (output array does not count).
Try Examples
Custom:
Approach
Prefix × Suffix Products
Phase 1: fill ans[] with left prefix products (L→R). Phase 2: sweep right, multiply each ans[i] by running right suffix (R→L). No division needed — O(1) extra space.
Array State
nums[]
ans[]
Variables
Phase
i
Prefix/Suffix
ans[i]
Step Logic
Press ▶ Play or Next Step to begin.
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
ans[0]=1; prefix pass L→R: ans[i] = ans[i-1] * nums[i-1]
2
suffix=1; pass R→L: ans[i] *= suffix; suffix *= nums[i]
3
Result is ans[] (no division used)
Time
O(n)
Space
O(1) extra
Why It Works

ans[i] = product of all left × product of all right. The prefix pass fills left products into ans[] directly. The suffix pass multiplies the right products in-place using a running variable. We reuse the output array itself, so no extra space is needed beyond a single scalar.