Product of Array Except Self - Problem
Given an integer array nums, return an array answer where answer[i] is equal to the product of all elements in nums except nums[i].
For example, if nums = [1,2,3,4], then answer = [24,12,8,6] because:
answer[0] = 2×3×4 = 24(all except index 0)answer[1] = 1×3×4 = 12(all except index 1)answer[2] = 1×2×4 = 8(all except index 2)answer[3] = 1×2×3 = 6(all except index 3)
Important constraints:
- You must write an algorithm that runs in O(n) time
- You cannot use the division operation
- All products are guaranteed to fit in a 32-bit integer
This problem tests your ability to think creatively about prefix and suffix products - a fundamental technique used in many advanced algorithms!
Input & Output
example_1.py — 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.py — With Negative Numbers
$
Input:
nums = [-1,1,0,-3,3]
›
Output:
[0,0,9,0,0]
💡 Note:
Since there's a 0 in the array, all products except the one at index 2 will be 0. For index 2: product = (-1)×1×(-3)×3 = 9.
example_3.py — Two Elements
$
Input:
nums = [2,3]
›
Output:
[3,2]
💡 Note:
For index 0: product = 3. For index 1: product = 2. This is the minimum array size case.
Visualization
Tap to expand
Understanding the Visualization
1
Map the Assembly Line
Each array element represents a production station with its efficiency multiplier
2
Calculate Left Production
For each station, calculate cumulative production from all stations to its left
3
Calculate Right Production
Traverse right-to-left, multiplying left production by running right production
4
Get Final Efficiency
Each position now contains total production when that station is removed
Key Takeaway
🎯 Key Insight: By calculating left products in one pass and right products in another, we can determine the 'production without each station' efficiently in O(n) time and O(1) extra space.
Time & Space Complexity
Time Complexity
O(n²)
For each of n elements, we iterate through n-1 other elements
⚠ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space (excluding the output array)
✓ Linear Space
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
- You must write an algorithm that runs in O(n) time
- You cannot use the division operation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code