Skip to content

Commit 4f97d39

Browse files
committed
Optimize memory complexity
1 parent f3bd95f commit 4f97d39

File tree

1 file changed

+8
-5
lines changed
  • prefix-product/238_Product_of_Array_Except_Self

1 file changed

+8
-5
lines changed

prefix-product/238_Product_of_Array_Except_Self/solution.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,19 @@ def product_except_self(nums: list[int]) -> list[int]:
77
"""
88

99
length = len(nums)
10-
left_prefix = [1] * length
11-
right_prefix = [1] * length
10+
left = 1
11+
right = 1
12+
output = [1] * length
1213

1314
for index in range(length - 1):
14-
left_prefix[index + 1] *= nums[index] * left_prefix[index]
15+
left *= nums[index]
16+
output[index + 1] *= left
1517

1618
for index in range(length - 1, 0, -1):
17-
right_prefix[index - 1] *= nums[index] * right_prefix[index]
19+
right *= nums[index]
20+
output[index - 1] *= right
1821

19-
return [l * r for l, r in zip(left_prefix, right_prefix)]
22+
return output
2023

2124

2225
assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6], 'Test 1 failed'

0 commit comments

Comments
 (0)