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
Product of Array Except SelfInput:1234index 0index 1index 2index 3Calculate products excluding each elementanswer[0] = 2 × 3 × 4 = 24answer[1] = 1 × 3 × 4 = 12answer[2] = 1 × 2 × 4 = 8answer[3] = 1 × 2 × 3 = 6Output:241286
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
Asked in
Google 45 Amazon 38 Facebook 32 Apple 28
89.5K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen