Goal
Given an array nums, build an array result where result[i] equals the product of all elements in nums except nums[i], without using division.
Key Idea (Intuition)
For each index i, the answer is the product of all elements to its left times the product of all elements to its right.
We can compute this in two linear passes using a single running product variable: first fill result[i] with the left product for each index, then traverse from right to left and multiply in the right product.
Initialization
- Create
resultwith lengthn. -
Set
product = 1— a running product variable.
It will represent the left product of the current index during the left-to-right traversal and the right product of the current index during the right-to-left traversal.
Traversal — Left to Right
For each index i from 0 to n-1:
- Write the current
productintoresult[i]— this is the left product for index i. - Update
productby multiplying withnums[i]so it becomes the left product for the next index.
Traversal — Right to Left
Reset product = 1 and iterate i from n-1 down to 0:
In this pass, product represents the right product for the current index.
result[i]currently holds the left product for indexi. Multiply it by the currentproductto factor in the right product.- Update
productby multiplying withnums[i]so it becomes the right product for the previous index in the next step.
Return
After both passes, result contains the product of all elements except self for each index. Return result.