Skip to content

Commit df77b95

Browse files
author
Joseph Luce
authored
Update 238_product_of_array_except_self.md
1 parent 0dd37dc commit df77b95

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

leetcode/medium/238_product_of_array_except_self.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,33 @@ class Solution:
3535
curr_prod *= n
3636
return result
3737
```
38+
39+
## Best Solution (Constant Space)
40+
- Runtime: O(N)
41+
- Space: O(1)
42+
- N = Number of elements in array
43+
44+
Similar to the solution above, instead of creating two arrays, we can first create an array for the products to the right of each number.
45+
This array can then be used as the final result, we can then calculate the left products as we modify the first array from left to right.
46+
This is constant space, assuming the returned result array is not considered extra space.
47+
48+
```
49+
class Solution:
50+
def productExceptSelf(self, nums: List[int]) -> List[int]:
51+
if len(nums) == 0:
52+
return []
53+
result = self.calc_left_product(nums[::-1])[::-1] # right products
54+
curr_prod = 1
55+
for index, n in enumerate(nums):
56+
result[index] *= curr_prod
57+
curr_prod *= n
58+
return result
59+
60+
def calc_left_product(self, nums):
61+
result = [1]*len(nums)
62+
curr_prod = nums[0]
63+
for index, n in enumerate(nums[1:], 1):
64+
result[index] = curr_prod
65+
curr_prod *= n
66+
return result
67+
```

0 commit comments

Comments
 (0)