File tree 4 files changed +114
-0
lines changed
product-of-array-except-self
4 files changed +114
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Dict
2
+
3
+
4
+ class Solution :
5
+ # Time: O(n)
6
+ # Space: O(n)
7
+ # ---
8
+ # 1. Prepare a table for caching. Initially put trivial answers for n = 1, 2.
9
+ # Space: O(n)
10
+ cacheTableOfAnswerByN : Dict [int , int ] = {1 : 1 , 2 : 2 }
11
+
12
+ def climbStairs (self , n : int ) -> int :
13
+ # 2. Use caching.
14
+ # Time: O(1)
15
+ try : return self .cacheTableOfAnswerByN [n ]
16
+ except KeyError :
17
+ # 3. Simply, the answers follow Fibonacci sequence. Use recursion.
18
+ # O(n)
19
+ answerBeforeTwoSteps = self .climbStairs (n - 2 )
20
+ # 4. Cache the answer during recursion.
21
+ self .cacheTableOfAnswerByN [n - 2 ] = answerBeforeTwoSteps
22
+ answerBeforeOneStep = self .climbStairs (n - 1 )
23
+ self .cacheTableOfAnswerByN [n - 1 ] = answerBeforeOneStep
24
+ return answerBeforeTwoSteps + answerBeforeOneStep
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+ from typing import Set
3
+ from typing import Tuple
4
+
5
+
6
+ class Solution :
7
+ target : int
8
+ candidates : List [int ]
9
+ answers : Set [Tuple [int ]]
10
+
11
+ # Time: O(k^N)
12
+ # Space: O(N^2)
13
+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
14
+ self .target = target
15
+ self .candidates = candidates
16
+ self .answers = set ()
17
+ self .findAnswers (0 , [])
18
+ return list (self .answers )
19
+
20
+ def findAnswers (self , currentSum : int , nums : List [int ]):
21
+ assert currentSum < self .target , "Given sum should be smaller than the target."
22
+ for num in self .candidates :
23
+ if currentSum + num < self .target :
24
+ # 1. Continue finding.
25
+ # Time: O(k^N)
26
+ # Space: O(N^2). Max total size of all "nums" = 1 + 2 + ... + N.
27
+ self .findAnswers (currentSum + num , nums + [num ])
28
+ if currentSum + num > self .target :
29
+ # 2. Stop finding.
30
+ continue
31
+ if currentSum + num == self .target :
32
+ # 3. Add the answer.
33
+ self .answers .add (tuple (sorted (list (nums + [num ]))))
34
+ return
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 ))
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+ from typing import Dict
3
+
4
+
5
+ class Solution :
6
+ # Time: O(n)
7
+ # Space: O(n)
8
+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
9
+ # 1. Make a map {target - num : index of num} with the list nums.
10
+ # Time: O(n)
11
+ # Space: O(n)
12
+ mapOfSubtractedValueToIndex : Dict [int , int ] = ({
13
+ target - num : index for index , num in enumerate (nums )
14
+ })
15
+
16
+ # 2. ForEach num in nums, get value from the map.
17
+ # Time: O(n)
18
+ # Space: O(n)
19
+ result : List [int ] = None
20
+ for indexOfNum , num in enumerate (nums ):
21
+ try :
22
+ indexOfSubtractedValue = mapOfSubtractedValueToIndex [num ]
23
+ if indexOfSubtractedValue == indexOfNum :
24
+ continue
25
+ # 3. Return the index of num in nums and the value from the map.
26
+ return [indexOfNum , indexOfSubtractedValue ]
27
+ except KeyError :
28
+ continue
You can’t perform that action at this time.
0 commit comments