Skip to content

Commit 4e2753d

Browse files
committed
Add a solution to product-of-array-except-self problem.
1 parent a70a9fe commit 4e2753d

File tree

1 file changed

+28
-0
lines changed
  • product-of-array-except-self

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
from functools import reduce
3+
4+
5+
class Solution:
6+
# Time: O(n)
7+
# Space: O(n)
8+
def productExceptSelf(self, nums: List[int]) -> List[int]:
9+
size: int = len(nums)
10+
if size == 1:
11+
return [1]
12+
# 1. Cut the array at the middle.
13+
# Time: O(1)
14+
# Space: O(n)
15+
indexToCut: int = len(nums) // 2
16+
left: List[int] = nums[0:indexToCut]
17+
right: List[int] = nums[indexToCut:size]
18+
19+
# 2. Divide, conquer, and merge. But no benefit in complexity.
20+
# Time: O(n)
21+
# Space: O(n)
22+
return self.multiplyToAll(self.productExceptSelf(left), self.calculateProductAll(right)) + self.multiplyToAll(self.productExceptSelf(right), self.calculateProductAll(left))
23+
24+
def calculateProductAll(self, nums: List[int]) -> int:
25+
return reduce(lambda x, y: x * y, nums)
26+
27+
def multiplyToAll(self, nums: List[int], multiplier: int) -> List[int]:
28+
return list(map(lambda num: multiplier * num, nums))

0 commit comments

Comments
 (0)