|
| 1 | +from typing import List |
| 2 | +import doctest |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def productExceptSelf(self, nums: List[int]) -> List[int]: |
| 6 | + """ |
| 7 | + Given an integer array nums, return an array answer such that |
| 8 | + answer[i] is equal to the product of all the elements of nums except nums[i]. |
| 9 | +
|
| 10 | + The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. |
| 11 | +
|
| 12 | + This solution runs in O(n) time and O(1) extra space (excluding output), |
| 13 | + without using division. |
| 14 | +
|
| 15 | + >>> Solution().productExceptSelf([1, 2, 3, 4]) |
| 16 | + [24, 12, 8, 6] |
| 17 | + >>> Solution().productExceptSelf([-1, 1, 0, -3, 3]) |
| 18 | + [0, 0, 9, 0, 0] |
| 19 | + >>> Solution().productExceptSelf([0, 0, 0]) |
| 20 | + [0, 0, 0] |
| 21 | + >>> Solution().productExceptSelf([0, 1, 2, 3]) |
| 22 | + [6, 0, 0, 0] |
| 23 | + >>> Solution().productExceptSelf([0, 0, 1]) |
| 24 | + [0, 0, 0] |
| 25 | + >>> Solution().productExceptSelf([-1, -2, -3]) |
| 26 | + [6, 3, 2] |
| 27 | + >>> Solution().productExceptSelf([1, 2]) |
| 28 | + [2, 1] |
| 29 | + >>> Solution().productExceptSelf([1, 1, 1]) |
| 30 | + [1, 1, 1] |
| 31 | + >>> Solution().productExceptSelf([-30, 30, -30, 30]) |
| 32 | + [-27000, 27000, -27000, 27000] |
| 33 | + >>> Solution().productExceptSelf([5, 0, 0, 5]) |
| 34 | + [0, 0, 0, 0] |
| 35 | + """ |
| 36 | + n = len(nums) |
| 37 | + answer = [1] * n |
| 38 | + |
| 39 | + # Left pass: Compute prefix products |
| 40 | + left_product = 1 |
| 41 | + for i in range(n): |
| 42 | + answer[i] *= left_product |
| 43 | + left_product *= nums[i] |
| 44 | + |
| 45 | + # Right pass: Compute suffix products and multiply into answer |
| 46 | + right_product = 1 |
| 47 | + for i in range(n - 1, -1, -1): |
| 48 | + answer[i] *= right_product |
| 49 | + right_product *= nums[i] |
| 50 | + |
| 51 | + return answer |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + # Run doctests |
| 55 | + doctest.testmod() |
| 56 | + |
| 57 | + # Additional manual execution example |
| 58 | + sol = Solution() |
| 59 | + test_cases = [ |
| 60 | + [1, 2, 3, 4], |
| 61 | + [-1, 1, 0, -3, 3], |
| 62 | + [0, 0, 0], |
| 63 | + [0, 1, 2, 3], |
| 64 | + [0, 0, 1], |
| 65 | + [-1, -2, -3], |
| 66 | + [1, 2], |
| 67 | + [1, 1, 1], |
| 68 | + [-30, 30, -30, 30], |
| 69 | + [5, 0, 0, 5] |
| 70 | + ] |
| 71 | + |
| 72 | + print("\nRunning additional test cases:") |
| 73 | + for case in test_cases: |
| 74 | + result = sol.productExceptSelf(case) |
| 75 | + print(f"Input: {case} -> Output: {result}") |
| 76 | + |
0 commit comments