Product of Array Except Self
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.
Constraints:
- 2 <= nums.length <= 10^5
- -30 <= nums[i] <= 30
- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Input Format:
- An integer array nums
Output Format:
- An array answer where answer[i] is equal to the product of all the elements of nums except nums[i]
Examples:
Example 1:
Input:
nums = [1,2,3,4]
Output:
[24,12,8,6]
Explanation:
[24,12,8,6] means: - 24 is the product of all array elements except 1 - 12 is the product of all array elements except 2 - 8 is the product of all array elements except 3 - 6 is the product of all array elements except 4
Example 2:
Input:
nums = [-1,1,0,-3,3]
Output:
[0,0,-9,0,0]
Explanation:
With a zero in the array, most of the output elements become 0 except for the element corresponding to the zero, which becomes the product of all other elements.
Solutions
Left and Right Product Arrays
Create two arrays to represent the product of all elements to the left and the product of all elements to the right of each element. Then multiply these two products to get the answer for each position.
Optimized Space Approach
Optimize space by using the output array to store the left products, and then compute the right products on-the-fly while building the result.
Algorithm Walkthrough
Example input: nums = [1,2,3,4]
Step-by-step execution:
- Initialize result array: [?, ?, ?, ?]
- Calculate left products:
- leftProducts[0] = 1 (no elements to the left)
- leftProducts[1] = 1 * 1 = 1
- leftProducts[2] = 1 * 2 = 2
- leftProducts[3] = 2 * 3 = 6
- Calculate right products:
- rightProducts[3] = 1 (no elements to the right)
- rightProducts[2] = 1 * 4 = 4
- rightProducts[1] = 4 * 3 = 12
- rightProducts[0] = 12 * 2 = 24
- Calculate final result:
- result[0] = leftProducts[0] * rightProducts[0] = 1 * 24 = 24
- result[1] = leftProducts[1] * rightProducts[1] = 1 * 12 = 12
- result[2] = leftProducts[2] * rightProducts[2] = 2 * 4 = 8
- result[3] = leftProducts[3] * rightProducts[3] = 6 * 1 = 6
- Final result: [24, 12, 8, 6]
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize how the left and right product arrays are built and combined to create the final output.
Key visualization elements:
- left product calculation
- right product calculation
- final multiplication
Implementation Notes
This problem tests the ability to manipulate arrays efficiently. The key insight is to calculate products from both left and right directions to avoid division. For interview practice, focus on the space-optimized O(1) extra space solution.