Skip to content

Commit 3eb0b1b

Browse files
author
Joseph Luce
authored
Create 238_product_of_array_except_self.md
1 parent 0cf59b3 commit 3eb0b1b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# 238. Product of Array Except Self
2+
3+
## Dynamic Programming Approach
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of elements in array
7+
8+
The idea is to calculate the products going from left to right, then again going right to left.
9+
Storing these calculations as two arrays will allow one last calculation to find the products from the left and right for each number.
10+
11+
```
12+
class Solution:
13+
def productExceptSelf(self, nums: List[int]) -> List[int]:
14+
if len(nums) == 0:
15+
return []
16+
left, right = self.calc_left_product(nums), self.calc_left_product(nums[::-1])[::-1]
17+
result = [1]*len(nums)
18+
for index, n in enumerate(zip(left, right)):
19+
result[index] = n[0]*n[1]
20+
return result
21+
22+
def calc_left_product(self, nums):
23+
result = [1]*len(nums)
24+
curr_prod = nums[0]
25+
for index, n in enumerate(nums[1:], 1):
26+
result[index] = curr_prod
27+
curr_prod *= n
28+
return result
29+
```

0 commit comments

Comments
 (0)