From 6858d4e8040fbbb7ac310e91b1e64e1969c63a0f Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 2 Jul 2026 04:51:16 -0600 Subject: [PATCH] adding updates --- .../round_1/08_product_of_array_excep_self.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/my_project/interviews/google_top_exercises/round_1/08_product_of_array_excep_self.py diff --git a/src/my_project/interviews/google_top_exercises/round_1/08_product_of_array_excep_self.py b/src/my_project/interviews/google_top_exercises/round_1/08_product_of_array_excep_self.py new file mode 100644 index 00000000..f6b7ed90 --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/08_product_of_array_excep_self.py @@ -0,0 +1,35 @@ +from typing import List + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + """ + Calculate product of all elements except self without division. + + Strategy: Two-pass with prefix and suffix products + - First pass: Build prefix products (product of all elements to the left) + - Second pass: Build suffix products (product of all elements to the right) + - Result[i] = prefix[i] * suffix[i] + + Optimization: Use output array to store prefix, then multiply by suffix in-place + + Time: O(n), Space: O(1) excluding output array + """ + + n = len(nums) + answer = [1] * n + + # First pass: Calculate prefix products + # answer[i] contains product of all elements to the left of i + prefix = 1 + for i in range(n): + answer[i] = prefix + prefix *= nums[i] + + # Second pass: Calculate suffix products and multiply with prefix + # For each position, multiply existing prefix with product of all elements to the right + suffix = 1 + for i in range(n - 1, -1, -1): + answer[i] *= suffix + suffix *= nums[i] + + return answer \ No newline at end of file