File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments