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 Self INPUT nums = [1, 2, 3, 4] 1 i=0 2 i=1 3 i=2 4 i=3 For each index i: answer[i] = product of all elements except nums[i] Example: answer[0] = 2 * 3 * 4 = 24 Example: answer[1] = 1 * 3 * 4 = 12 No division allowed! ALGORITHM STEPS 1 Initialize result array result = [1, 1, 1, 1] 2 Left pass (prefix) Store left products 1 1 2 6 --> 3 Right pass (suffix) Multiply with right products <-- 24 12 8 6 4 Return result O(n) time, O(1) extra space Time: O(n) - two passes Space: O(1) - reuse result array FINAL RESULT answer = [24, 12, 8, 6] 24 i=0 12 i=1 8 i=2 6 i=3 Verification: answer[0] = 2*3*4 = 24 OK answer[1] = 1*3*4 = 12 OK answer[2] = 1*2*4 = 8 OK answer[3] = 1*2*3 = 6 OK All products verified! No division used Key Insight: For each position, the product = (product of all elements to the left) * (product of all elements to the right). By computing prefix products in one pass and suffix products in another, we achieve O(n) time without division. TutorialsPoint - Product of Array Except Self | Space Optimized - Single Array
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