📘
Product of Array Except Self
MediumArrays & Strings
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:
- First, we calculate the total product of all elements: 1⋅2⋅3⋅4=24
- Then, for each element, we find the product of all other elements by using the total product and the current element:
- For the first element (1), the product is 2⋅3⋅4=24
- For the second element (2), the product is 1⋅3⋅4=12
- For the third element (3), the product is 1⋅2⋅4=8
- For the fourth element (4), the product is 1⋅2⋅3=6
- The final output is the array of these products: 24 12 8 6
Constraints:
- 2 <= len(nums) <= 10^5
- -30 <= nums[i] <= 30
- The product of any prefix or suffix fits in a 32-bit integer
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.