|
| 1 | +def product_except_self(nums: list[int]) -> list[int]: |
| 2 | + """ |
| 3 | + Computes for each element the product of all other elements in the array. |
| 4 | + |
| 5 | + :param nums: Input array of integers. May contain negatives and zeros. |
| 6 | + :return: Array where output[i] = product of all elements except nums[i] |
| 7 | + """ |
| 8 | + |
| 9 | + length = len(nums) |
| 10 | + left_prefix = [1] * length |
| 11 | + right_prefix = [1] * length |
| 12 | + |
| 13 | + for index in range(length - 1): |
| 14 | + left_prefix[index + 1] *= nums[index] * left_prefix[index] |
| 15 | + |
| 16 | + for index in range(length - 1, 0, -1): |
| 17 | + right_prefix[index - 1] *= nums[index] * right_prefix[index] |
| 18 | + |
| 19 | + return [l * r for l, r in zip(left_prefix, right_prefix)] |
| 20 | + |
| 21 | + |
| 22 | +assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6], 'Test 1 failed' |
| 23 | +assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0], 'Test 2 failed' |
0 commit comments