|
| 1 | +from typing import List |
| 2 | + |
| 3 | +def product_except_self(nums: List[int]) -> List[int]: |
| 4 | + """ |
| 5 | + Returns an array `ans` where ans[i] is the product of all elements of |
| 6 | + `nums` except nums[i], without using division and in O(n) time. |
| 7 | +
|
| 8 | + This implementation uses O(1) extra space (ignoring the output array) |
| 9 | + by: |
| 10 | + 1. Building prefix products directly into the output array. |
| 11 | + 2. Scanning from right to left and multiplying by a running suffix product. |
| 12 | +
|
| 13 | + Time Complexity: O(n) |
| 14 | + Space Complexity: O(1) extra (output array not counted) |
| 15 | +
|
| 16 | + Args: |
| 17 | + nums: List[int] - input list of integers (length >= 1) |
| 18 | +
|
| 19 | + Returns: |
| 20 | + List[int] - product array as described above |
| 21 | +
|
| 22 | + Example: |
| 23 | + >>> product_except_self([1,2,3,4]) |
| 24 | + [24, 12, 8, 6] |
| 25 | + """ |
| 26 | + n = len(nums) |
| 27 | + if n == 0: |
| 28 | + return [] |
| 29 | + |
| 30 | + # ans[i] will hold product of nums[0..i-1] after first pass |
| 31 | + ans = [1] * n |
| 32 | + for i in range(1, n): |
| 33 | + ans[i] = ans[i - 1] * nums[i - 1] |
| 34 | + |
| 35 | + # suffix holds product of nums[i+1..n-1] |
| 36 | + suffix = 1 |
| 37 | + for i in range(n - 1, -1, -1): |
| 38 | + ans[i] *= suffix |
| 39 | + suffix *= nums[i] |
| 40 | + |
| 41 | + return ans |
| 42 | + |
| 43 | + |
| 44 | +# Optional: straightforward version using explicit prefix and suffix arrays |
| 45 | +def product_except_self_extra_space(nums: List[int]) -> List[int]: |
| 46 | + """ |
| 47 | + Alternate implementation that uses O(n) extra space for clarity. |
| 48 | + """ |
| 49 | + n = len(nums) |
| 50 | + if n == 0: |
| 51 | + return [] |
| 52 | + |
| 53 | + pre = [1] * n |
| 54 | + suf = [1] * n |
| 55 | + ans = [1] * n |
| 56 | + |
| 57 | + for i in range(1, n): |
| 58 | + pre[i] = pre[i - 1] * nums[i - 1] |
| 59 | + |
| 60 | + for i in range(n - 2, -1, -1): |
| 61 | + suf[i] = suf[i + 1] * nums[i + 1] |
| 62 | + |
| 63 | + for i in range(n): |
| 64 | + ans[i] = pre[i] * suf[i] |
| 65 | + |
| 66 | + return ans |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + # quick manual checks |
| 71 | + examples = [ |
| 72 | + ([1, 2, 3, 4], [24, 12, 8, 6]), |
| 73 | + ([0, 0], [0, 0]), |
| 74 | + ([0, 1, 2, 3], [6, 0, 0, 0]), |
| 75 | + ([5], [5]), |
| 76 | + ] |
| 77 | + for arr, expected in examples: |
| 78 | + out = product_except_self(arr) |
| 79 | + print(f"{arr} -> {out} (expected {expected})") |
0 commit comments