Product of All Elements Except Self
Implement productExceptSelf
Given an array
nums, return an array result where result[i] is the product of every element in nums except nums[i] — without using division, and ideally in O(n) time.
Multiplying everything except one index, one index at a time, repeats almost the same work over and over. The prefix productPrefix ProductThe running product of every element from the start of the array up to (but not including) a given index — the multiplicative sibling of a prefix sum. trick reuses that work: sweep once left-to-right building the product of everything to the left of each index, then once right-to-left building the product of everything to the right, multiplying the two halves together as you go.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Example 3:
Input: nums = [2,3]
Output: [3,2]
+ 8 hidden test cases run on Submit.
Constraints:
- ●
2 ≤ nums.length ≤ 10⁵ - ●
-30 ≤ nums[i] ≤ 30 - ●
The product of any prefix or suffix fits in a 32-bit integer - ●
Division is not allowed as a solving technique
nums =
[1, 2, 3, 4]