Product of Array Except Self - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,4]
›
Output:
[24,12,8,6]
💡 Note:
For index 0: product = 2×3×4 = 24. For index 1: product = 1×3×4 = 12. For index 2: product = 1×2×4 = 8. For index 3: product = 1×2×3 = 6.
Example 2 — With Zero
$
Input:
nums = [-1,1,0,-3,3]
›
Output:
[0,0,9,0,0]
💡 Note:
Since there's a 0 in the array, all positions except index 2 will have product 0. At index 2 (skipping the 0): product = (-1)×1×(-3)×3 = 9.
Example 3 — Small Array
$
Input:
nums = [2,3]
›
Output:
[3,2]
💡 Note:
For index 0: skip nums[0]=2, product = 3. For index 1: skip nums[1]=3, product = 2.
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.
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array [1,2,3,4] - need product excluding each element
2
Calculate Products
For each position, multiply all other elements
3
Result Array
Output [24,12,8,6] where each element is product of all others
Key Takeaway
🎯 Key Insight: Product except current = (left products) × (right products), allowing O(n) time solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code