medium +20 pts

Product of All Except Zeros Handling

Compute the product of every element except the current one while correctly handling zeros.

Given a list `nums` of integers (possibly empty), write a function `product_except_self(nums)` that returns a new list where each element at index `i` is the product of all the elements in `nums` except `nums[i]`. Important rules: - Your solution must not use division. - Handle zeros correctly: the product of all other elements is 0 if there is more than one zero in the list. - For an empty list, return an empty list. - The order of the returned list must match the original indices. Implement the function exactly with the signature `def product_except_self(nums):`.

Constraints

- `0 <= len(nums) <= 10^5` - Each `nums[i]` is an integer in the range `[-1000, 1000]`. - The product of all elements except any single element fits within a Python integer. - Expected time complexity: `O(n)`. Expected space complexity: `O(1)` extra space (excluding output).

Example

```python
# Example 1
product_except_self([1, 2, 3, 4])
# Output: [24, 12, 8, 6]

# Example 2
product_except_self([0, 1, 2])
# Output: [2, 0, 0]

# Example 3
product_except_self([0, 0])
# Output: [0, 0]

# Example 4
product_except_self([])
# Output: []
```
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Separate the cases: if there are two or more zeros, all results are zero.
If there is exactly one zero, only the position of that zero gets the product of the non-zero elements; all others are zero.
If there are no zeros, the result at each index is the total product divided by `nums[i]`, but since division is forbidden, you must compute it with two passes (left and right products) instead.
You can achieve O(1) extra space by storing the result array and overwriting it with cumulative products from left and then right.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.