From 74a3652595a043fdeacf0ba79358ff49fcf2ad1b Mon Sep 17 00:00:00 2001 From: Ruslan Serebriakov Date: Sat, 25 May 2024 23:43:38 +0200 Subject: [PATCH] Fixing time complexity issue to O(n) as requested in issue #1. --- product_of_array_except_self.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/product_of_array_except_self.py b/product_of_array_except_self.py index 7cec5f2..22e84e8 100644 --- a/product_of_array_except_self.py +++ b/product_of_array_except_self.py @@ -2,11 +2,18 @@ def product_except_self(nums): n = len(nums) result = [1] * n + left_products = [1] * n + right_products = [1] * n + + for i in range(1, n): + left_products[i] = left_products[i - 1] * nums[i - 1] + + for i in range(n - 2, -1, -1): + right_products[i] = right_products[i + 1] * nums[i + 1] + for i in range(n): - for j in range(n): - if i != j: - result[i] *= nums[j] - + result[i] = left_products[i] * right_products[i] + return result # Test the function with the example input