Product of Array Except Self
Product of Array Except Self
Prefix/Postfix
Problem Statement
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
. The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
Example
Example 1:
Input: nums = [1,2,3,4]
nums: [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Output: [24,12,8,6]
Solution
The problem can be solved in O(n) time and O(1) extra space (the output array does not count as extra space) by first calculating the prefix products, and then multiplying by the postfix products in a second pass.
Algorithm Steps
- Initialize an answer array of the same size as `nums` with all 1s.
- Calculate the prefix products and store them in the answer array.
- Initialize a `postfix` variable to 1.
- Iterate through the array from right to left.
- Multiply the current element in the answer array by `postfix`.
- Update `postfix` by multiplying it with the current element in `nums`.
- Return the answer array.
Product of Array Except Self
Prefix/Postfix Product Approach
Input: nums = [1, 2, 3, 4]
Output: []
Progress1 / 1
Ready to start the visualization
Nums
1
2
3
4
Result Array
Product of Array Except Self Solution