File tree 1 file changed +49
-0
lines changed 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 322. Coin Change
3
+
4
+ use a queue for BFS & iterate through the coins and check the amount is down to 0.
5
+ use a set to the visited check.
6
+
7
+ ## Time and Space Complexity
8
+
9
+ ```
10
+ TC: O(n * Amount)
11
+ SC: O(Amount)
12
+ ```
13
+
14
+ #### TC is O(n * Amount):
15
+ - sorting the coins = O(n log n)
16
+ - reversing the coins = O(n)
17
+ - iterating through the queue = O(Amount)
18
+ - iterating through the coins and check the remaining amount is down to 0 = O(n)
19
+
20
+ #### SC is O(Amount):
21
+ - using a queue to store (the remaining amount, the count of coins) tuple = O(Amount)
22
+ - using a set to store the visited check = O(Amount)
23
+ '''
24
+ class Solution :
25
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
26
+ if amount == 0 :
27
+ return 0
28
+ if len (coins ) == 1 and coins [0 ] == amount :
29
+ return 1
30
+
31
+ coins .sort () # TC: O(n log n)
32
+ coins .reverse () # TC: O(n)
33
+
34
+ queue = deque ([(amount , 0 )]) # SC: O(Amount)
35
+ visited = set () # SC: O(Amount)
36
+
37
+ while queue : # TC: O(Amount)
38
+ remain , count = queue .popleft ()
39
+
40
+ for coin in coins : # TC: O(n)
41
+ next_remain = remain - coin
42
+
43
+ if next_remain == 0 :
44
+ return count + 1
45
+ if next_remain > 0 and next_remain not in visited :
46
+ queue .append ((next_remain , count + 1 ))
47
+ visited .add (next_remain )
48
+
49
+ return - 1
You can’t perform that action at this time.
0 commit comments