v9.1.1
Menu

Product of Array Except Self

mediumPROArrays & StringsGoogle DSA

Given an array nums, return an array where each element is the product of all elements except itself. Do not use division.

Output space-separated.

Example

Input
1,2,3,4
Output
24 12 8 6
Reasoning
  • Input: nums is a list of integers, here 1,2,3,4. Each output position ii gets ∏j≠ixj\prod_{j \ne i} x_j, the product of every entry except xix_i.
  • Position 0 drops the 11: 2⋅3⋅4=242 \cdot 3 \cdot 4 = 24.
  • Position 1 drops the 22: 1⋅3⋅4=121 \cdot 3 \cdot 4 = 12.
  • Position 2 drops the 33: 1⋅2⋅4=81 \cdot 2 \cdot 4 = 8.
  • Position 3 drops the 44: 1⋅2⋅3=61 \cdot 2 \cdot 3 = 6.
  • Output: a list the same length as the input, printed space-separated as 24 12 8 6.
  • Notice why division is banned: with a zero in the input, as in −1,1,0,−3,3-1, 1, 0, -3, 3, every position except the zero's own includes that 00 and becomes 00. Only the zero's position survives, at (−1)(1)(−3)(3)=9(-1)(1)(-3)(3) = 9, giving 0 0 9 0 0. Dividing a total product by xix_i can't recover that 99.

Constraints

  • 2 <= len(nums) <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix fits in a 32-bit integer

More from Google DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.