post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1997354/Simple-Python-Solution
class Solution: def maxProduct(self, words: List[str]) -> int: ans=0 for i in range(len(words)): for j in range(i+1, len(words)): flag=False for k in words[i]: if k in words[j]: flag=True break if not flag: ans=max(ans, len(words[i])*len(words[j])) return ans
maximum-product-of-word-lengths
Simple Python Solution
Siddharth_singh
0
80
maximum product of word lengths
318
0.601
Medium
5,500
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1798207/Python-O(26n**2)-time.-O(n)-space-solution-(no-bit-manipulation)
class Solution: def maxProduct(self, words: List[str]) -> int: n = len(words) res = 0 charset = defaultdict(set) for i in range(n): word = words[i] for c in word: charset[c].add(i) for i in range(n-1): for j in range(i+1, n): w1, w2 = words[i], words[j] flag = True for c in range(ord('a'), ord('z') + 1): char = chr(c) s = charset[char] if i in s and j in s: flag = False if flag: res = max(res, len(w1) * len(w2)) return res
maximum-product-of-word-lengths
Python O(26n**2) time,. O(n) space solution (no bit manipulation)
byuns9334
0
113
maximum product of word lengths
318
0.601
Medium
5,501
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1696586/Python3-accepted-solution
class Solution: def maxProduct(self, words: List[str]) -> int: words = sorted(words,key=len)[::-1] max_ = 0 for i in range(len(words)-1): for j in range(i+1, len(words)): if(len("".join(set(words[i]).intersection(set(words[j])))) == 0): #print(words[i],words[j]) if(len(words[i])*len(words[j]) > max_): #print(words[i],words[j]) max_ = len(words[i])*len(words[j]) return max_
maximum-product-of-word-lengths
Python3 accepted solution
sreeleetcode19
0
85
maximum product of word lengths
318
0.601
Medium
5,502
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1561716/Python-solution
class Solution: def maxProduct(self, words: List[str]) -> int: max_val=0 for current_word in range(len(words)-1): for word in words[current_word+1:]: if len(set(words[current_word]).intersection(set(word)))==0: val=len(words[current_word])*len(word) if val>max_val: max_val=val return max_val
maximum-product-of-word-lengths
Python solution
msrini111
0
85
maximum product of word lengths
318
0.601
Medium
5,503
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1236967/Python-Solution
class Solution: def maxProduct(self, words): mapping = {} for word in words: mapping[word] = set(word) max_value = 0 n = len(words) for i in range(n - 1): set1 = mapping[words[i]] for j in range(i + 1, n): set2 = mapping[words[j]] good = True if len(set1) < len(set2): for ch in set1: if ch in set2: good = False break else: for ch in set2: if ch in set1: good = False break if good: max_value = max(max_value, len(words[i]) * len(words[j])) return max_value
maximum-product-of-word-lengths
Python Solution
mariandanaila01
0
157
maximum product of word lengths
318
0.601
Medium
5,504
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1235119/Python3-calculate-pairwise-distance-and-check-orthogonal-word-vectors.
class Solution: def vec_dotprod(self, vec1, vec2): x = 0 for a, b in zip(vec1, vec2): x += a*b return x def maxProduct(self, words: List[str]) -> int: word_matrix = [] n = len(words) for w in words: vec = [0 for _ in range(26)] # word embedding for k in range(len(w)): vec[ord(w[k]) - 97] += 1 # # print(chr(97), chr(97+25)) word_matrix.append(vec) prod = [[0] * n for _ in range(n)] for i in range(n): for j in range(i+1, n): prod[i][j]= self.vec_dotprod(word_matrix[i], word_matrix[j]) max_l = 0 for i in range(n): for j in range(i+1, n): if prod[i][j] == 0: max_l = max(max_l, len(words[i]) * len(words[j])) return (max_l)
maximum-product-of-word-lengths
[Python3] calculate pairwise distance and check orthogonal word vectors.
markxc02
0
44
maximum product of word lengths
318
0.601
Medium
5,505
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1233707/Simple-solution-in-Python-using-Set-operations
class Solution: def maxProduct(self, words: List[str]) -> int: n = len(words) hashmap = dict() i = 0 ans = 0 for word in words: hashmap[i] = set(word) i += 1 for i in range(0, n - 1): a = hashmap[i] for j in range(i + 1, n): b = hashmap[j] if not len(a.intersection(b)): ans = max(ans, len(words[i]) * len(words[j])) return ans
maximum-product-of-word-lengths
Simple solution in Python using Set operations
amoghrajesh1999
0
53
maximum product of word lengths
318
0.601
Medium
5,506
https://leetcode.com/problems/bulb-switcher/discuss/535399/PythonJSJavaC%2B%2B-sol-by-perfect-square.-w-Visualization
class Solution: def bulbSwitch(self, n: int) -> int: # Only those bulds with perferct square number index will keep "ON" at last. return int(n**0.5)
bulb-switcher
Python/JS/Java/C++ sol by perfect square. [w/ Visualization]
brianchiang_tw
20
1,200
bulb switcher
319
0.481
Medium
5,507
https://leetcode.com/problems/bulb-switcher/discuss/1220041/Python3-simple-one-liner-solution
class Solution: def bulbSwitch(self, n: int) -> int: return int(n**0.5)
bulb-switcher
Python3 simple one-liner solution
EklavyaJoshi
7
479
bulb switcher
319
0.481
Medium
5,508
https://leetcode.com/problems/bulb-switcher/discuss/788489/Python3-brain-teaser
class Solution: def bulbSwitch(self, n: int) -> int: return int(sqrt(n))
bulb-switcher
[Python3] brain teaser
ye15
2
427
bulb switcher
319
0.481
Medium
5,509
https://leetcode.com/problems/bulb-switcher/discuss/788489/Python3-brain-teaser
class Solution: def bulbSwitch(self, n: int) -> int: return isqrt(n)
bulb-switcher
[Python3] brain teaser
ye15
2
427
bulb switcher
319
0.481
Medium
5,510
https://leetcode.com/problems/bulb-switcher/discuss/2835762/ONE-WORDororMATH-SOLUTION-oror-VERY-EASY-TO-UNDERSTAND-oror-50-MS
class Solution: def bulbSwitch(self, n: int) -> int: return int(n**(1/2))
bulb-switcher
ONE WORD||MATH SOLUTION || VERY EASY TO UNDERSTAND || 50 MS
thezealott
1
13
bulb switcher
319
0.481
Medium
5,511
https://leetcode.com/problems/bulb-switcher/discuss/2823581/Python-Solution-(1-Liner-or-Math-or-Perfect-Square)-%2B-Explication-!
class Solution: def bulbSwitch(self, n: int) -> int: return isqrt(n)
bulb-switcher
Python Solution (1 Liner | Math | Perfect Square) + Explication !
nvshah
0
4
bulb switcher
319
0.481
Medium
5,512
https://leetcode.com/problems/bulb-switcher/discuss/523039/Python3-simple-solution
class Solution: def bulbSwitch(self, n: int) -> int: bulb_on = 0 v = 2 while n >= 1: bulb_on += 1 n -= v + 1 v += 2 return bulb_on
bulb-switcher
Python3 simple solution
tjucoder
0
332
bulb switcher
319
0.481
Medium
5,513
https://leetcode.com/problems/create-maximum-number/discuss/2167532/O(k(m%2Bn)).-Python-Solution-with-monotonically-decreasing-stack.-Commented-for-clarity.
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: def maximum_num_each_list(nums: List[int], k_i: int) -> List[int]: # monotonically decreasing stack s = [] m = len(nums) - k_i for n in nums: while s and s[-1] < n and m > 0: s.pop() m -= 1 s.append(n) s = s[:len(s)-m] # very important return s def greater(a, b, i , j): # get the number which is lexiographically greater while i< len(a) or j < len(b): if i == len(a): return False if j == len(b): return True if a[i] > b[j]: return True if a[i] < b[j]: return False i += 1 # we increment until each of their elements are same j += 1 def merge(x_num, y_num): n = len(x_num) m = len(y_num) i = 0 j = 0 s = [] while i < n or j < m: a = x_num[i] if i < n else float("-inf") b = y_num[j] if j < m else float("-inf") if a > b or greater(x_num, y_num, i , j): # greater(x_num, y_num, i , j): this function is meant for check which list has element lexicographically greater means it will iterate through both arrays incrementing both at the same time until one of them is greater than other. chosen = a i += 1 else: chosen = b j += 1 s.append(chosen) return s max_num_arr = [] for i in range(k+1): # we check for all values of k and find the maximum number we can create for that value of k and we repeat this for all values of k and then at eacch time merge the numbers to check if arrive at optimal solution first = maximum_num_each_list(nums1, i) second = maximum_num_each_list(nums2, k-i) merged = merge(first, second) # these two conditions are required because list comparison in python only compares the elements even if one of their lengths is greater, so I had to add these conditions to compare elements only if length is equal. # Alternatively you can avoid this and convert them both to int and then compare, but I wanted to this as it is somewhat more efficient. if len(merged) == len(max_num_arr) and merged > max_num_arr: max_num_arr = merged elif len(merged) > len(max_num_arr): max_num_arr = merged return max_num_arr
create-maximum-number
O(k(m+n)). Python Solution with monotonically decreasing stack. Commented for clarity.
saqibmubarak
2
443
create maximum number
321
0.288
Hard
5,514
https://leetcode.com/problems/create-maximum-number/discuss/1467230/Python3-greedy
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: def fn(arr, k): """Return largest sub-sequence of arr of size k.""" ans = [] for i, x in enumerate(arr): while ans and ans[-1] < x and len(ans) + len(arr) - i > k: ans.pop() if len(ans) < k: ans.append(x) return ans ans = [0] * k for i in range(k+1): if k - len(nums2) <= i <= len(nums1): val1 = fn(nums1, i) val2 = fn(nums2, k-i) cand = [] i1 = i2 = 0 while i1 < len(val1) or i2 < len(val2): if val1[i1:] >= val2[i2:]: cand.append(val1[i1]) i1 += 1 else: cand.append(val2[i2]) i2 += 1 ans = max(ans, cand) return ans
create-maximum-number
[Python3] greedy
ye15
2
531
create maximum number
321
0.288
Hard
5,515
https://leetcode.com/problems/create-maximum-number/discuss/2346274/Runtime%3A-216-ms-or-Memory-Usage%3A-14.2-MB
class Solution: def maxNumber(self, n_1: List[int], n_2: List[int], k: int) -> List[int]: def f1(maxum,s1,s2): n1, n2 = -1, -1 if M - s1 > maxum: n1 = max(n_1[s1:s1+maxum]) elif s1 < M: n1 = max(n_1[s1:]) if N - s2 > maxum: n2 = max(n_2[s2:s2+maxum]) elif s2 < N: n2 = max(n_2[s2:]) return n1,n2 M, N = len(n_1), len(n_2) r, l = [], [[0,0]] for x in range(k): n_l, n_r = [], [] for st in l: n1, n2 = f1(M + N - st[0] - st[1] - k + 1 + x , st[0], st[1]) if n1 > n2: n_r.append(n1) n_l.append([st[0]+n_1[st[0]:].index(n1)+1,st[1]]) elif n1 < n2: n_r.append(n2) n_l.append([st[0],st[1]+n_2[st[1]:].index(n2)+1]) elif n1 == n2 and n1 != -1: n_r.append(n1) n_l.append([st[0]+n_1[st[0]:].index(n1)+1,st[1]]) n_r.append(n2) n_l.append([st[0],st[1]+n_2[st[1]:].index(n1)+1]) nr = -1 for i in range(len(n_r)): if n_r[i] > nr: n_n_l = set(); n_n_l.add((n_l[i][0],n_l[i][1])); nr = n_r[i] elif n_r[i] == nr: n_n_l.add((n_l[i][0],n_l[i][1])) r.append(nr) l = n_n_l return r
create-maximum-number
Runtime: 216 ms, | Memory Usage: 14.2 MB
vimla_kushwaha
1
135
create maximum number
321
0.288
Hard
5,516
https://leetcode.com/problems/create-maximum-number/discuss/2105459/Python-or-Easy-to-understand-or-Greedy-%2B-Dynamic-Programminng
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: m = len(nums1) n = len(nums2) dp = {} # get the max number string with "length" from index "i" in nums1 and index "j" in nums2 # using number string to easy to compare def getMaxNumberString(i, j, length): if length == 0: return "" # using memoization to optimize for the overlapping subproblems key = (i, j, length) if key in dp: return dp[key] # greedy to find the possible max digit from nums1 and nums2 # 1) bigger digit in the higher position of the number will get bigger number # 2) at the same time, we need to ensure that we still have enough digits to form a number with "length" digits # try to find the possible max digit from index i in nums1 index1 = None for ii in range(i, m): if (m - ii + n - j) < length: break if index1 is None or nums1[index1] < nums1[ii]: index1 = ii # try to find the possible max digit from index j in nums2 index2 = None for jj in range(j, n): if (m - i + n - jj) < length: break if index2 is None or nums2[index2] < nums2[jj]: index2 = jj maxNumberStr = None if index1 is not None and index2 is not None: if nums1[index1] > nums2[index2]: maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1) elif nums1[index1] < nums2[index2]: maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1) else: # get the same digit from nums1 and nums2, so need to try two cases and get the max one maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)) elif index1 is not None: maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1) elif index2 is not None: maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1) dp[key] = maxNumberStr return maxNumberStr result_str = getMaxNumberString(0, 0, k) # number string to digit array result = [] for c in result_str: result.append(int(c)) return result
create-maximum-number
Python | Easy to understand | Greedy + Dynamic Programminng
AdairCLO
0
168
create maximum number
321
0.288
Hard
5,517
https://leetcode.com/problems/create-maximum-number/discuss/1982077/Python3-or-Monotonic-Stack-or-Greedy
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: def find_k_max_number_in_an_array(nums, k): drop_possible = len(nums) - k n = len(nums) stack = [] for i, val in enumerate(nums): while stack and drop_possible and stack[-1] < val: drop_possible -= 1 stack.pop() stack.append(val) return stack[:k] def merge_two_array(arr1, arr2): #print(arr1, arr2) return [max(arr1, arr2).pop(0) for _ in arr1 + arr2] def compare_two_array(arr1, arr2): """ determine whether arr1 is greater than arr2 """ if not arr2: return True i = j = 0 n = len(arr1) while i < n and j < n: if arr1[i] > arr2[j]: return True elif arr1[i] < arr2[j]: return False i += 1 j += 1 return True ans = 0 for i in range(k + 1): p = k - i if i > len(nums1) or p > len(nums2): continue # get this two array by solving function find_k_max_number_in_an_array # using similar concept of 402. Remove K Digits first_arr = find_k_max_number_in_an_array(nums1, i) second_arr = find_k_max_number_in_an_array(nums2, p) # merge two array with everytime taking lexicographily larger list # https://leetcode.com/problems/create-maximum-number/discuss/77286/Short-Python-Ruby-C%2B%2B # see explanation curr_arr = merge_two_array(first_arr, second_arr) #print(curr_arr) # can be directly use python max function if compare_two_array(curr_arr, ans): ans = curr_arr # ans = max(ans, curr_arr) if ans else curr_arr #print(ans) return ans
create-maximum-number
Python3 | Monotonic Stack | Greedy
showing_up_each_day
0
310
create maximum number
321
0.288
Hard
5,518
https://leetcode.com/problems/coin-change/discuss/2058537/Python-Easy-2-DP-approaches
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp=[math.inf] * (amount+1) dp[0]=0 for coin in coins: for i in range(coin, amount+1): if i-coin>=0: dp[i]=min(dp[i], dp[i-coin]+1) return -1 if dp[-1]==math.inf else dp[-1]
coin-change
Python Easy 2 DP approaches
constantine786
32
3,800
coin change
322
0.416
Medium
5,519
https://leetcode.com/problems/coin-change/discuss/2058537/Python-Easy-2-DP-approaches
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: def coinChangeInner(rem, cache): if rem < 0: return math.inf if rem == 0: return 0 if rem in cache: return cache[rem] cache[rem] = min(coinChangeInner(rem-x, cache) + 1 for x in coins) return cache[rem] ans = coinChangeInner(amount, {}) return -1 if ans == math.inf else ans
coin-change
Python Easy 2 DP approaches
constantine786
32
3,800
coin change
322
0.416
Medium
5,520
https://leetcode.com/problems/coin-change/discuss/478739/Python3-DP-solution-with-comments-to-help-understand-what-is-happening-and-why
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: numCoins = len(coins) # Values in this array equal the number of coins needed to achieve the cost of the index minCoins = [amount + 1] * (amount + 1) minCoins[0] = 0 # Loop through every needed amount for i in range(amount + 1): # Loop through every coin value for coin in coins: # Check that the coin is not bigger than the current amount if coin <= i: # minCoins[i]: number of coins needed to make amount i # minCoins[i-coin]: number of coins needed to make the amount before adding # the current coin to it (+1 to add the current coin) minCoins[i] = min(minCoins[i], minCoins[i-coin] + 1) # Check if any combination of coins was found to create the amount if minCoins[amount] == amount + 1: return -1 # Return the optimal number of coins to create the amount return minCoins[amount]
coin-change
Python3 DP solution with comments to help understand what is happening and why
jhacker
26
2,700
coin change
322
0.416
Medium
5,521
https://leetcode.com/problems/coin-change/discuss/861503/Python3-dp
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: @cache def fn(x): """Return fewest number of coins to make up to x.""" if x == 0: return 0 if x < 0: return inf return min(1 + fn(x - coin) for coin in coins) return fn(amount) if fn(amount) < inf else -1
coin-change
[Python3] dp
ye15
5
276
coin change
322
0.416
Medium
5,522
https://leetcode.com/problems/coin-change/discuss/861503/Python3-dp
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [0] + [inf]*amount for x in range(amount): if dp[x] < inf: for coin in coins: if x + coin <= amount: dp[x+coin] = min(dp[x+coin], 1 + dp[x]) return dp[-1] if dp[-1] < inf else -1
coin-change
[Python3] dp
ye15
5
276
coin change
322
0.416
Medium
5,523
https://leetcode.com/problems/coin-change/discuss/861503/Python3-dp
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [0] + [inf]*amount for x in range(1, amount+1): for coin in coins: if coin <= x: dp[x] = min(dp[x], 1 + dp[x-coin]) return dp[-1] if dp[-1] < inf else -1
coin-change
[Python3] dp
ye15
5
276
coin change
322
0.416
Medium
5,524
https://leetcode.com/problems/coin-change/discuss/610710/PythonGo-O(-c*n-)-sol-by-DP-w-Hint
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # initialization for dp_table dp_table = [ float('inf') for _ in range(amount+1) ] # base case for $0 dp_table[0] = 0 for value in range(1, amount+1): for coin in coins: if coin > value: # coin value is too big, can not make change with current coin continue # update dp_table, try to make change with coin dp_table[value] = min( (dp_table[value], dp_table[ value - coin ] + 1) ) if dp_table[amount] != float('inf'): # Accept, return total count of coin change return dp_table[amount] else: # Reject, no solution return -1
coin-change
Python/Go O( c*n ) sol by DP [ w/ Hint ]
brianchiang_tw
5
831
coin change
322
0.416
Medium
5,525
https://leetcode.com/problems/coin-change/discuss/610710/PythonGo-O(-c*n-)-sol-by-DP-w-Hint
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: @cache def dp(cur_amount): ## base cases if cur_amount == 0: # current amount can be fully changed with given coins return 0 if cur_amount < 0: # current amount can not be change with given coins return float('inf') ## general cases # select the optimal method to change with smallest number of coins min_change = min( dp(cur_amount-coin) for coin in coins ) + 1 return min_change # --------------------------------------------- res = dp(amount) return res if res != float('inf') else -1
coin-change
Python/Go O( c*n ) sol by DP [ w/ Hint ]
brianchiang_tw
5
831
coin change
322
0.416
Medium
5,526
https://leetcode.com/problems/coin-change/discuss/610710/PythonGo-O(-c*n-)-sol-by-DP-w-Hint
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # -------------------------------------------------------------------- dp_table={0:0} def dp(amount): if amount < 0: return -1 elif amount in dp_table: return dp_table[amount] best_change = float('inf') for coin in coins: best_for_subproblem = dp(amount-coin) if best_for_subproblem == -1: continue best_change = min(best_change, best_for_subproblem + 1) dp_table[amount] = best_change if best_change != float('inf') else -1 return dp_table[amount] # -------------------------------------------------------------------- return dp(amount)
coin-change
Python/Go O( c*n ) sol by DP [ w/ Hint ]
brianchiang_tw
5
831
coin change
322
0.416
Medium
5,527
https://leetcode.com/problems/coin-change/discuss/2164625/Python3-solution-DP-top-down-approach
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = {} for i in coins: dp[i] = 1 def getResult(amount): if amount == 0: return 0 if amount in dp: return dp[amount] k = float("inf") for i in coins: if i<=amount: k = min(k,1 + getResult(amount-i)) dp[amount] = k return dp[amount] k = getResult(amount) return k if k!=float("inf") else -1
coin-change
📌 Python3 solution DP top down approach
Dark_wolf_jss
4
95
coin change
322
0.416
Medium
5,528
https://leetcode.com/problems/coin-change/discuss/1106130/Python-DP-recursive-easy-to-understand
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if not coins: return 0 cache = {} def dp(amount): if amount in cache: return cache[amount] if amount == 0: return 0 tmp = [] for coin in coins: if amount - coin >= 0: tmp.append(dp(amount - coin)) else: tmp.append(float('inf')) min_coins = min(tmp) + 1 cache[amount] = min_coins return min_coins result = dp(amount) if result != float('inf'): return result return -1
coin-change
Python DP recursive easy to understand
dlog
4
699
coin change
322
0.416
Medium
5,529
https://leetcode.com/problems/coin-change/discuss/2059283/Python-Simple-Python-Solution-Using-DP-oror-82-Faster
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [ 10000 for _ in range(amount+1)] dp[0] = 0 for i in range(amount+1): for coin in coins: if coin <= i: dp[i] = min(dp[i],1 + dp[i-coin]) if dp[-1] == 10000: return -1 else: return dp[-1]
coin-change
[ Python ] ✅✅ Simple Python Solution Using DP || 82 % Faster✌👍
ASHOK_KUMAR_MEGHVANSHI
3
360
coin change
322
0.416
Medium
5,530
https://leetcode.com/problems/coin-change/discuss/1847630/Python-Bottom-up-DP-solution-explained
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0 or not coins: return 0 # this dp will hold the number of coins # required for every amount from 0..amount dp = [float('inf')] * (amount+1) # to have a sum of zero # we don't need any coins i.e 0 dp[0] = 0 # brute force, we'll calculate # the coins needed for every amount # starting from 1 since we've calculated 0 for a in range(1, amount+1): # for every amount, we'll # try to form coins with every # available coin for c in coins: # if the current amount is less # than the current coin, you can't # make that amount with this coin # so skip it. i.e. if a = 2 and coin = 5 # you should not bother computing anything here if a-c >= 0: # otherwise, you check the min # of the num(coins) for current amount # and the 1 plus the coins required # by amount-c i.e. to make the amount 0 # for e.g. if amount = 7 and coin = 3, # we can say the coins needed to make 7 # would be the coin of denomination 4 (+1) and # the number of coins taken to reach 3 # => 1 + dp[3] so that we can easily reach the sum i.e 7 dp[a] = min(dp[a], dp[a-c]+1) # we need to return -1 if we weren't able to find # an answer i.e. no updates were made and the amount # still has the initial value we had set i.e float('inf') return dp[amount] if dp[amount] != float('inf') else -1
coin-change
[Python] Bottom-up DP solution explained
buccatini
3
264
coin change
322
0.416
Medium
5,531
https://leetcode.com/problems/coin-change/discuss/1767785/Python-Solution-using-Dynamic-Programming-or-Detailed-Explanation
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: MAX_INT = 100000 if amount == 0: return 0 if amount in coins: return 1 dp = [MAX_INT]*(amount+1) dp[0] = 0 dp[1] = 1 if 1 in coins else -1 for i in range(1, amount+1): if i in coins: dp[i] = 1 else: minValForAllCoins = MAX_INT for coin in coins: if i >= coin: minValForAllCoins = min(dp[i-coin] + 1, minValForAllCoins) dp[i] = minValForAllCoins return dp[-1] if dp[-1] != MAX_INT else -1
coin-change
Python Solution using Dynamic Programming | Detailed Explanation
anushkabajpai
3
487
coin change
322
0.416
Medium
5,532
https://leetcode.com/problems/coin-change/discuss/1261083/Python-O(n*amount)-8-lines-Easy-to-understand-DP-Solution
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # If given amount is zero, then there are '0' ways to form this amount using any set of coins if amount == 0: return 0 # There is no way the result ,i.e. the no. of coins to form the amount, can be greater than the actual given amount so we initiate our dp table with 'amount+1' to compare minimums dp = [amount+1] * (amount+1) dp[0] = 0 # we are not interseted in the 'amount' less than current coin's value as there is no possible way to include this coin and produce an amount less than it. for i in range(len(coins)): for j in range(coins[i], amount + 1): dp[j] = min(dp[j], dp[j - coins[i]] + 1) return -1 if dp[-1] > amount else dp[-1] ############################################################################################## # Simple example using DP Table: coins = [2, 3]; amount = 3 # Used a 2D DP Table to visulize the idea of the algorithm, but you can also use 1D table to perform the same (like the solution) # 0 1 2 3 (Amount) # 0 [ 0 4 4 4 ] --> Our initial values # (Coins) 2 [ 0 4 1 4 ] --> Min. no of coins to create the amount if including 2 # 3 [ 0 4 1 1 ] --> Min. no of coins to create the amount if including 2 and 3 # Keep the values the same for the 'amount' less than current coin's value ##############################################################################################
coin-change
[Python] O(n*amount), 8 lines, Easy to understand DP Solution
yashjain039
3
221
coin change
322
0.416
Medium
5,533
https://leetcode.com/problems/coin-change/discuss/1838052/Simple-DFS-using-a-template
class Solution: def coinChange(self, coins, amount): @lru_cache(maxsize=None) def dfs(curr): if curr > amount: return math.inf if curr == amount: return 0 return min(dfs(curr + val) + 1 for val in coins) result = dfs(0) return -1 if result == math.inf else result
coin-change
Simple DFS using a template;
GeneBelcher
2
284
coin change
322
0.416
Medium
5,534
https://leetcode.com/problems/coin-change/discuss/1838052/Simple-DFS-using-a-template
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: travel_days = set(days) pass_duration = [1, 7, 30] @lru_cache(maxsize=None) def dfs(day): if day > 365: return 0 if day in travel_days: return min(dfs(day + d) + c for d, c in zip(pass_duration, costs)) return dfs(day + 1) return dfs(0)
coin-change
Simple DFS using a template;
GeneBelcher
2
284
coin change
322
0.416
Medium
5,535
https://leetcode.com/problems/coin-change/discuss/1761259/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: @lru_cache(None) def dp(i: int) -> int: # base case if i == 0: return 0 if i < 0: return -1 # recurrence minimum = float('inf') for coin in coins: res = dp(i-coin) if res >= 0 and res < minimum: minimum = 1 + res if minimum == float('inf'): return -1 return minimum return dp(amount)
coin-change
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
183
coin change
322
0.416
Medium
5,536
https://leetcode.com/problems/coin-change/discuss/1761259/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [float('inf')]*(amount+1) dp[0] = 0 for coin in coins: for x in range(coin, amount+1): dp[x] = min(dp[x], dp[x-coin]+1) return dp[amount] if dp[amount] != float('inf') else -1
coin-change
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
2
183
coin change
322
0.416
Medium
5,537
https://leetcode.com/problems/coin-change/discuss/2403302/Python3-or-Solved-Bottom-Up-Using-DP-%2B-Tabulation
class Solution: #Time-Complexity: O(amount * len(coins)), we solve amount number of subproblems, but in #worst case, we iterate through each and every coin in coins array! #Space-Complexity:O(amount) def coinChange(self, coins: List[int], amount: int) -> int: #bottom up approach -> Use dp table in process of filling it left to right(tabulation) #indices will dictate our subproblems from amount 0 to orignal amount! dp = [amount+1] * (amount + 1) #solve the trivial subproblem: amount 0 dp[0] = 0 #sort the coins array in increasing order so we consider using coins #of smallest denomination first! coins.sort() #and then, we want to solve subproblems bottom up from amount 1 to original! for i in range(1, amount+1, 1): for coin in coins: #if we use current coin we are iterating on as last coin, we are #left with remainder amount to sum up to, which we also want to use #least number of coins to do so-> Hence, the optimal substructure property #of solving subproblems optimally to get optimal solution to main problem! #If you also draw recursion tree, the subproblems ultimately overlap! remainder = i - coin if(remainder >= 0): #add 1 since we are still using one of the coins as last one! dp[i] = min(dp[i], dp[remainder] + 1) else: break #edge case: we can't add up to amount given the coins! #we know we can't sum up to amount if at index amount, we still have garbage value! if(dp[amount] == (amount+1)): return -1 return dp[amount]
coin-change
Python3 | Solved Bottom-Up Using DP + Tabulation
JOON1234
1
43
coin change
322
0.416
Medium
5,538
https://leetcode.com/problems/coin-change/discuss/2259418/Python-Dynamic-full-working-solution-with-explanation
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # Time: O(n*n) and Space:O(n) dp = [amount + 1] * (amount + 1) # bottom-up dp from 0 to amount indexes with amount+1 value in it dp[0] = 0 # with 0 coins we can get 0 amount # we will go from amount=1 to amounts given value, computing in between that how many number of coins is required to reach a. # this for loops will build a dp which we will use to check previous dp values for a in range(1, amount + 1): for c in coins: # if a - c >= 0: # if amount - coin goes in minus skip it dp[a] = min(dp[a], 1 + dp[a - c]) # we add 1 to previous value cause it satisfies if condition return dp[amount] if dp[amount] != amount + 1 else -1
coin-change
Python Dynamic full working solution with explanation
DanishKhanbx
1
279
coin change
322
0.416
Medium
5,539
https://leetcode.com/problems/coin-change/discuss/2222627/Solution-with-VIDEO-EXPLANATION
class Solution(object): def coinChange(self, coins, amount): dp=[amount+1]*(amount+1) dp[0]=0 for i in range(1,amount+1): for c in coins: if i-c>=0: dp[i]=min(dp[i],1+dp[i-c]) if dp[amount]>amount: return -1 return dp[amount]
coin-change
Solution with VIDEO EXPLANATION
Egan_707
1
80
coin change
322
0.416
Medium
5,540
https://leetcode.com/problems/coin-change/discuss/2060422/Python3-oror-Recursion-oror-Memoization-oror-Faster-Solution
class Solution(object): def __init__(self): self.mem = {0: 0} def coinChange(self, coins, amount): coins.sort() minCoins = self.getMinCoins(coins, amount) if minCoins == float('inf'): return -1 return minCoins def getMinCoins(self, coins, amount): if amount in self.mem: return self.mem[amount] minCoins = float('inf') for c in coins: if amount - c < 0: break numCoins = self.getMinCoins(coins, amount - c) + 1 minCoins = min(numCoins, minCoins) self.mem[amount] = minCoins return minCoins
coin-change
Python3 || Recursion || Memoization || Faster Solution
bvian
1
113
coin change
322
0.416
Medium
5,541
https://leetcode.com/problems/coin-change/discuss/2010907/python3-Runtime%3A-1493ms-81.19-memory%3A-14.1mb-62.20
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: ways = [float('inf')] * (amount + 1) ways[0] = 0 for coin in coins: for amt in range(len(ways)): if coin <= amt: ways[amt] = min(ways[amt], ways[amt - coin] + 1) return ways[amount] if ways[amount] != float('inf') else -1
coin-change
python3 Runtime: 1493ms 81.19% memory: 14.1mb 62.20%
arshergon
1
70
coin change
322
0.416
Medium
5,542
https://leetcode.com/problems/coin-change/discuss/1669308/Straightforward-bottom-up-and-top-down-DP-solutions-for-Coin-Change
class Solution: def coinChange(self, coins: 'List[int]', amount: 'int') -> 'int': dp = [float('inf')] * (amount+1) dp[0] = 0 for amount_left in range(min(coins), amount+1): children = [dp[(amount_left-coin)]+1 for coin in coins if (amount_left-coin)>=0] if children: dp[amount_left] = min(children) return dp[amount] if dp[amount] != float('inf') else -1
coin-change
Straightforward bottom-up and top-down DP solutions for Coin Change
NinjaBlack
1
118
coin change
322
0.416
Medium
5,543
https://leetcode.com/problems/coin-change/discuss/1669308/Straightforward-bottom-up-and-top-down-DP-solutions-for-Coin-Change
class Solution: def coinChange(self, coins: 'List[int]', amount: 'int') -> 'int': @cache def dp(amount_left): if amount_left == 0: return 0 children = [dp(amount_left-coin)+1 for coin in coins if (amount_left-coin)>=0] if children: return min(children) else: return float('inf') return dp(amount) if dp(amount) != float('inf') else -1
coin-change
Straightforward bottom-up and top-down DP solutions for Coin Change
NinjaBlack
1
118
coin change
322
0.416
Medium
5,544
https://leetcode.com/problems/coin-change/discuss/1666872/Python-or-Simple-and-intuitive
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # initiate a 1d dp list mx=amount+1 dp=[0]+[mx for _ in range(amount)] #dp list is generated for smaller values first. this will be used to compute higer values - classic memoization approach for i in range(1,len(dp)): # iterate for every coin that we have for each amount as every coin can be added infinite times for c in coins: if i-c>=0: dp[i]=min(dp[i],dp[i-c]+1) return dp[-1] if dp[-1]!=amount+1 else -1
coin-change
Python | Simple and intuitive
vishyarjun1991
1
332
coin change
322
0.416
Medium
5,545
https://leetcode.com/problems/coin-change/discuss/1105374/Python-DP-Solution
class Solution: def coinChange(self, coins: List[int], sumx: int) -> int: n = len(coins) t = [[999999999 for i in range(sumx+1)] for j in range(n+1)] for i in range(1, n + 1): t[i][0] = 0 for j in range(1, (sumx + 1)): if j % coins[0] == 0: t[1][j] = j // coins[0] else: t[1][j] = 999999999 for i in range(2, n + 1): for j in range(1, (sumx + 1)): if coins[i - 1] > j: t[i][j] = t[i-1][j] else: t[i][j] = min(t[i-1][j], 1 + t[i][j-coins[i-1]]) return -1 if t[n][sumx] == 999999999 else t[n][sumx]
coin-change
Python DP Solution
aishwaryanathanii
1
267
coin change
322
0.416
Medium
5,546
https://leetcode.com/problems/coin-change/discuss/955394/Python-DP-Top-Down-and-Bottom-Up-(%2B-Complexity-Analyses)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: ## Top Down Approach coins.sort() result = self._helper(coins, amount, {0:0}) # cache = {0:0} -> 0 amount requires 0 coins return [result, -1][result == float('inf')] # Return result iff it's not infinity. Else, return -1 def _helper(self, coins, amount, cache): if amount in cache: return cache[amount] result = float('inf') # Sentinel used here is infinity, (amount + 1) can also be chosen as it can't EVER be the answer for coin in coins: if amount - coin < 0: break # invalid path curr_result = self._helper(coins, amount - coin, cache) + 1 result = min(curr_result, result) cache[amount] = result return result
coin-change
Python - DP - Top Down & Bottom Up (+ Complexity Analyses)
noobie12
1
197
coin change
322
0.416
Medium
5,547
https://leetcode.com/problems/coin-change/discuss/955394/Python-DP-Top-Down-and-Bottom-Up-(%2B-Complexity-Analyses)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: ## Bottom Up Approach dp = [0] + [float('inf')] * amount # Zero amount means zero coins &amp; every other value is initialized to infinity for curr_amount in range(1, amount + 1): for coin in coins: if curr_amount >= coin: dp[curr_amount] = min(dp[curr_amount], dp[curr_amount - coin] + 1) # Sticking with the current value vs. Using the coin. # If we use the coin, the answer will be the anser to the subproblem at index (amount - coin) plus 1 (as we use the coin). return [dp[-1], -1][dp[-1] == float('inf')] # Return result iff it's not infinity. Else, return -1
coin-change
Python - DP - Top Down & Bottom Up (+ Complexity Analyses)
noobie12
1
197
coin change
322
0.416
Medium
5,548
https://leetcode.com/problems/coin-change/discuss/2845455/DP-bottom-to-top
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = [amount+1 for i in range(amount+1)] memo[0] = 0 for i in range(len(memo)): for j in coins: if i-j<0: continue memo[i] = min(memo[i],1+memo[i-j]) return memo[amount] if memo[amount]!=amount+1 else -1
coin-change
DP bottom to top
ychhhen
0
3
coin change
322
0.416
Medium
5,549
https://leetcode.com/problems/coin-change/discuss/2845256/Python3-Use-DP-%2B-Memo-to-find-the-minimum-number-of-coins-cnt
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = dict() def dp(n): if n == 0: return 0 if n < 0: return -1 if n in memo: return memo[n] res = float('INF') # Use a maximum value for coin in coins: subProblem = dp(n-coin) # Divide the problem to subproblem if subProblem == -1: continue res = min(res, subProblem + 1) if res != float('INF'): memo[n] = res else: memo[n] = -1 return memo[n] return dp(amount)
coin-change
[Python3] Use DP + Memo to find the minimum number of coins cnt
Cceline00
0
1
coin change
322
0.416
Medium
5,550
https://leetcode.com/problems/coin-change/discuss/2844703/Dynamic-Programming-explained-Python
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: coin_change = [1e9 for _ in range(amount + 1)] coin_change[0] = 0 for i in range(amount + 1): for coin in coins: if i - coin >= 0: coin_change[i] = min(coin_change[i], 1 + coin_change[i - coin]) return coin_change[amount] if coin_change[amount] < 1e9 else -1
coin-change
Dynamic Programming explained - Python
rere-rere
0
2
coin change
322
0.416
Medium
5,551
https://leetcode.com/problems/coin-change/discuss/2840019/BFS-Solution-beats-98
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: q = deque() q.append(amount) seen = set() steps = 0 while q: for _ in range(len(q)): remain = q.popleft() if remain == 0: return steps for c in coins: nxt= remain - c if nxt>= 0 and nxt not in seen: q.append(nxt) seen.add(nxt) steps += 1 return -1
coin-change
BFS Solution beats 98%
samuelmayna
0
3
coin change
322
0.416
Medium
5,552
https://leetcode.com/problems/coin-change/discuss/2837518/Python-DP-solution
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [0] for i in range(1,amount+1): m = sys.maxsize has_answer = False for coin in coins: if(i - coin >= 0 and dp[i - coin] != -1): has_answer = True m = min(m, dp[i - coin] + 1) if(not has_answer): m = -1 dp.append(m) return dp[-1]
coin-change
Python DP solution
charleswizards
0
4
coin change
322
0.416
Medium
5,553
https://leetcode.com/problems/coin-change/discuss/2821724/Python-or-Recursive-way-or-Dynamic-Programming
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: res = [float("inf")] def dfs(sum, count): if sum == amount: res[0] = min(res[0], count) return for num in coins: if sum+num <= amount: dfs(sum+num, count+1) dfs(0, 0) return res[0] if res[0]!= inf else -1
coin-change
Python | Recursive way | Dynamic Programming
ajay_gc
0
7
coin change
322
0.416
Medium
5,554
https://leetcode.com/problems/coin-change/discuss/2821724/Python-or-Recursive-way-or-Dynamic-Programming
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if not coins: return -1 dptable = [float("inf")]*(amount+1) dptable[0] = 0 for amount in range(1, amount+1): min_value = dptable[amount] for num in coins: if num<=amount: min_value = min(min_value, dptable[amount-num]) dptable[amount]= min_value+1 return dptable[-1] if dptable[-1] != inf else -1
coin-change
Python | Recursive way | Dynamic Programming
ajay_gc
0
7
coin change
322
0.416
Medium
5,555
https://leetcode.com/problems/coin-change/discuss/2786042/7-lines-of-DP-solution-(python)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = {i:float('inf') for i in range(amount+1)} dp[0] = 0 for i in range(1,amount+1): for c in coins: if i >= c: dp[i] = min(dp[i], 1+dp[i-c]) return dp[amount] if dp[amount] != float('inf') else -1
coin-change
7 lines of DP solution (python)
candymoon36
0
11
coin change
322
0.416
Medium
5,556
https://leetcode.com/problems/coin-change/discuss/2782296/Breaking-down-vs-Building-up
class Solution: coins = [] @functools.cache def soln(self, amount: int): if amount < 0: return int(10e9) if amount == 0: return 0 res = [self.soln(amount - v) + 1 for v in self.coins] return min(res) def coinChange(self, coins: List[int], amount: int) -> int: self.coins = coins res = self.soln(amount) return res if res < int(10e9) else -1
coin-change
Breaking down vs Building up
Abhi5415
0
5
coin change
322
0.416
Medium
5,557
https://leetcode.com/problems/coin-change/discuss/2782296/Breaking-down-vs-Building-up
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0: return 0 dp = [0] * (amount +1) # dp stores min number of coins needed to make [i] for i in range(1, amount+1): # dp[i] m = int(10e9) for j in coins: if i - j >= 0: m = min(m, dp[i-j] + 1) dp[i] = m print(dp) return dp[amount] if dp[amount] < 10e9 else -1
coin-change
Breaking down vs Building up
Abhi5415
0
5
coin change
322
0.416
Medium
5,558
https://leetcode.com/problems/coin-change/discuss/2776424/Python-Simple-3-Approach-or-Recursive-or-Iterative-Easy-DP
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = {} def bfs(amount, item): if item==0 and amount>=0: return float('inf')-1 if item>0 and amount==0: return 0 if item==1 and amount>0: return amount//coins[item-1] if amount%coins[item-1]==0 else float('inf')-1 if dp.get((item, amount),None) is not None: return dp[(item, amount)] if coins[item-1] <= amount: dp[(item, amount)] = min(bfs(amount, item-1), 1 + bfs(amount-coins[item-1], item)) else: dp[(item, amount)] = bfs(amount, item-1) return dp[(item, amount)] res = bfs(amount, len(coins)) return -1 if res == float('inf') else res
coin-change
✔️ [Python] Simple 3 Approach | Recursive | Iterative Easy DP
girraj_14581
0
20
coin change
322
0.416
Medium
5,559
https://leetcode.com/problems/coin-change/discuss/2776424/Python-Simple-3-Approach-or-Recursive-or-Iterative-Easy-DP
class Solution(): def coinChange(self, coins: List[int], amount: int) -> int: n = len(coins) dp = [[None]*(amount+1) for i in range(n+1)] for i in range(amount+1): dp[0][i] = float('inf')-1 if i%coins[0]==0: dp[1][i] = i//coins[0] else: dp[1][i] = float('inf')-1 for i in range(1, n+1): dp[i][0] = 0 for i in range(2,n+1): for j in range(1, amount+1): if coins[i-1] <= j: dp[i][j] = min(dp[i-1][j], 1 + dp[i][j - coins[i-1]]) else: dp[i][j] = dp[i-1][j] return -1 if dp[-1][-1] == float('inf') else dp[-1][-1]
coin-change
✔️ [Python] Simple 3 Approach | Recursive | Iterative Easy DP
girraj_14581
0
20
coin change
322
0.416
Medium
5,560
https://leetcode.com/problems/coin-change/discuss/2762521/Pythonor-from-front-to-endor-quicker-DP
# class Solution: # def __init__(self) -> None: # self.amounts = [-666 for _ in range(10002)] # def coinChange(self, coins: List[int], amount: int) -> int: # if amount == 0 : # return 0 # if amount < 0: # return -1 # if self.amounts[amount] != -666: # return self.amounts[amount] # now_min = amount+1 # for i in coins: # ans = self.coinChange(coins, amount-i) # if ans == -1: # continue # now_min = min(now_min, ans+1) # if now_min == amount+1: # self.amounts[amount] = -1 # else: # self.amounts[amount] = now_min # return self.amounts[amount] class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # Number of coins required to reach a given value (index represents value) dp = [None for _ in range(amount+1)] # Num coins to reach 0 dp[0] = 0 for i in range(1, len(dp)): for coin in coins: if i - coin >= 0 and dp[i-coin] is not None: if dp[i] is None or dp[i] > 1 + dp[i-coin]: dp[i] = 1 + dp[i-coin] result = dp[amount] if result is None: return - 1 return result
coin-change
Python| from front to end| quicker DP
lucy_sea
0
5
coin change
322
0.416
Medium
5,561
https://leetcode.com/problems/coin-change/discuss/2762516/Python-or-end-to-front-or-simple-but-slow-one
class Solution: def __init__(self) -> None: self.amounts = [-666 for _ in range(10002)] def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0 : return 0 if amount < 0: return -1 if self.amounts[amount] != -666: return self.amounts[amount] now_min = amount+1 for i in coins: ans = self.coinChange(coins, amount-i) if ans == -1: continue now_min = min(now_min, ans+1) if now_min == amount+1: self.amounts[amount] = -1 else: self.amounts[amount] = now_min return self.amounts[amount]
coin-change
Python | end to front | simple but slow one
lucy_sea
0
4
coin change
322
0.416
Medium
5,562
https://leetcode.com/problems/coin-change/discuss/2761293/Python-Dynamic-Programming-with-Memory
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = {i:-666 for i in range(amount+1)} def dp(Coins, Amount): res = float('inf') if Amount == 0: return 0 if Amount < 0: return -1 if memo[Amount] != -666: return memo[Amount] for coin in Coins: subProblem = dp(coins, Amount-coin) if subProblem == -1: continue res = min(res, subProblem + 1) memo[Amount] = -1 if res == float('inf') else res return memo[Amount] return dp(coins, amount)
coin-change
Python Dynamic Programming with Memory
Rui_Liu_Rachel
0
5
coin change
322
0.416
Medium
5,563
https://leetcode.com/problems/coin-change/discuss/2760913/Python-solution
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount<0: return -1 if amount==0: return 0 dp = [float("inf")]*(amount+1) dp[0] = 0 for i in range(1, amount+1): for c in coins: if i>=c: dp[i] = min(dp[i], dp[i-c]+1) return dp[amount] if dp[amount]!=float("inf") else -1 """ dp[0] = 0 dp[1] = dp[1-1]+1 = dp[0]+1 = 1 dp[2] = dp[2-1]+1 = dp[1]+1 = 2 => 1 dp[2-2]+1 = dp[0]+1 = 1 dp[3] = dp[3-1]+1 = dp[2]+1 = 2 => 2 dp[3-2]+1 = dp[1]+1 = 2 dp[4] = dp[4-1]+1 = dp[3]+1 = 3 => 2 dp[4-2]+1 = dp[2]+1 = 2 dp[5] = dp[5-1]+1 = dp[4]+1 = 3 => 1 dp[5-2]+1 = dp[3]+1 = 3 dp[5-5]+1 = dp[0]+1 = 1 """
coin-change
Python solution
gcheng81
0
5
coin change
322
0.416
Medium
5,564
https://leetcode.com/problems/coin-change/discuss/2731569/Python-Solution-or-O(coins-*-amount)-TC-SC-or-2D-Grid-Dynamic-Programming-Based
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: coins.sort() store = [[0 for _ in range(amount+1)] for _ in range(len(coins)+1)] for row in range(len(store)): for col in range(len(store[0])): if col == 0: store[row][col] = 0 elif row == 0: store[row][col] = float("inf") elif coins[row-1] > col: store[row][col] = store[row-1][col] else: store[row][col] = min( 1 + store[row][col - coins[row - 1]], store[row - 1][col] ) return store[-1][-1] if store[-1][-1] <= amount else -1
coin-change
Python Solution | O(coins * amount) TC, SC | 2D Grid Dynamic Programming Based
Gautam_ProMax
0
20
coin change
322
0.416
Medium
5,565
https://leetcode.com/problems/coin-change/discuss/2724592/Easy-Undertstanding-in-python
class Solution: def coinChange(self, arr: List[int], t: int) -> int: dp=[[-1 for i in range(t+1)]for i in range(len(arr)+1)] def fun(i,t): if t==0: return 0 if dp[i][t]!=-1: return dp[i][t] if i==len(arr): return 1e9 p=1e9 if t>=arr[i]: p=1+fun(i,t-arr[i]) np=fun(i+1,t) dp[i][t]=min(p,np) return dp[i][t] a=fun(0,t) return a if a != 1e9 else -1
coin-change
Easy Undertstanding in python
hemanth_12
0
10
coin change
322
0.416
Medium
5,566
https://leetcode.com/problems/coin-change/discuss/2723635/94-faster-85-less-space-python3-DP
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # A[i] = fewest number of coins needed to make sum i A = [0] + [-1] * amount # zero coins needed to make zero for i in range(1, amount + 1): # options are the last coin chosen options = [A[i-coin] for coin in coins if i - coin >= 0 and A[i-coin] != -1] A[i] = 1 + min(options) if possibilities else -1 return A[amount]
coin-change
94% faster, 85% less space python3 DP
jbradleyglenn
0
13
coin change
322
0.416
Medium
5,567
https://leetcode.com/problems/coin-change/discuss/2717615/Python-3-Sol.-easy-and-efficient
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: def coinChangeInner(rem, cache): if rem < 0: return math.inf if rem == 0: return 0 if rem in cache: return cache[rem] cache[rem] = min(coinChangeInner(rem-x, cache) + 1 for x in coins) return cache[rem] ans = coinChangeInner(amount, {}) return -1 if ans == math.inf else ans
coin-change
Python 3 Sol. easy and efficient
pranjalmishra334
0
12
coin change
322
0.416
Medium
5,568
https://leetcode.com/problems/coin-change/discuss/2713775/Python-3-Bottom-Up-Dynamic-Programming-Solution
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp_array = [amount+1 for i in range(amount+1)] dp_array[0] = 0 for i in range(amount+1): for coin in coins: if coin<=i: dp_array[i] = min(dp_array[i], 1+dp_array[i-coin]) return dp_array[amount] if dp_array[amount]<amount+1 else -1
coin-change
Python 3, Bottom Up Dynamic Programming Solution
paul1202
0
6
coin change
322
0.416
Medium
5,569
https://leetcode.com/problems/coin-change/discuss/2695484/coinChange
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # dp = [float('inf')] * (amount + 1) # dp[0] = 0 # for i in range(amount+1): # for coin in coins: # if i + coin > amount : # continue # dp[i + coin] = min(dp[i + coin], dp[i] + 1) # return dp[amount] if dp[amount] < float("inf") else -1 def dfs(memo, n): if memo[n]: # it's already calculated, simply return it return memo[n] if n == 0: return 0 memo[n] = float("inf") for coin in coins: if n - coin >= 0: memo[n] = min(memo[n], dfs(memo, n-coin)+1) return memo[n] memo = collections.defaultdict(int) tmp = dfs(memo, amount) return tmp if tmp != float("inf") else -1
coin-change
coinChange
langtianyuyu
0
4
coin change
322
0.416
Medium
5,570
https://leetcode.com/problems/coin-change/discuss/2639443/DPpython
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = ['*' for _ in range(amount+1)] def dp(coins, target)->int: res = float('inf') if(target == 0): return 0 if(target < 0): return -1 if(memo[target] != '*'): return memo[target] for coin in coins: temp = dp(coins, target-coin) if(temp == -1): continue res = min(res, 1+temp) if res == float('inf'): memo[target] = -1 else: memo[target] = res return memo[target] return dp(coins, amount)
coin-change
[DP]python
kuroko_6668
0
39
coin change
322
0.416
Medium
5,571
https://leetcode.com/problems/coin-change/discuss/2623942/Simple-python-code-with-explanation
class Solution: def coinChange(self, coins, amount): #store the amount+1 (value) in dp(array) (amount +1) times #because first index is 0 dp = [amount+1]*(amount+1) #change the firxt index value to 0 #because the no. of coins used to get value 0 is 0 dp[0] = 0 #this for loop is to iterate from 1 to amount for a in range(1,amount + 1): #this for loop is to iterate througth the coins for c in coins: #if the amount value is greater than or equal to the curr coin we can pick that coin if a >=c: #then we have to store #minimum of (amount)th index in dp(array) and #(1(we have picked the coin) + dp[a-c](and we have to pick fewmore coins which can sum up to (amount - curr coin))) dp[a] = min(dp[a] ,1+dp[a-c]) #at first we have stored the value (amount + 1) at all indexes #if the value is changed at (amount)th index in dp #then it will be less than or equal to amount #if it is changed if dp[amount] != amount + 1: #we can return the value at (amount)th index return dp[amount] #if it is not changed else: #then we cannot make the amount using the coins in the list(coins) #so return - 1 return -1
coin-change
Simple python code with explanation
thomanani
0
101
coin change
322
0.416
Medium
5,572
https://leetcode.com/problems/coin-change/discuss/2623907/Memory-usage-less-than-96.98
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [amount + 1]*(amount+1) dp[0] = 0 for a in range(1,amount+1): for c in coins: if a-c >= 0: dp[a] = min(dp[a],1+dp[a-c]) return dp[amount] if dp[amount] != amount+1 else -1
coin-change
Memory usage less than 96.98%
jayeshvarma
0
41
coin change
322
0.416
Medium
5,573
https://leetcode.com/problems/coin-change/discuss/2577943/BFS-faster-than-90
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if not amount: return 0 n = len(coins) queue = deque() count = 1 temp = [] flex = set() for i in range(n): s = amount - coins[i] if(s == 0): return count if (s > 0 and s not in flex): flex.add(s) temp.append(s) queue.append(temp) while(queue): res = queue.popleft() if not res: break count += 1 temp = [] for k in res: for i in range(n): s = k - coins[i] if (s == 0): return count if(s > 0 and s not in flex): flex.add(s) temp.append(s) queue.append(temp) return -1
coin-change
BFS faster than 90%
Sukhwinder_Singh
0
57
coin change
322
0.416
Medium
5,574
https://leetcode.com/problems/coin-change/discuss/2555484/Simple-Python3-Solution-Using-Tabluar-Method-oror-DP
class Solution: def coinChange(self, arr: List[int], s: int) -> int: n = len(arr) dp = [[-1 for _ in range(s+1)] for _ in range(n+1)] # initialization of 1st column for i in range(1,n+1): dp[i][0] = 0 # initialization of 1st row with max value for i in range(s+1): dp[0][i] = sys.maxsize # initialization of 2nd row for i in range(1,s+1): if i%arr[0]==0: dp[1][i] = i//arr[0] else: dp[1][i] = sys.maxsize # fill the remaining table for i in range(2,n+1): for j in range(1,s+1): if arr[i-1]<=j: dp[i][j] = min(dp[i][j-arr[i-1]]+1,dp[i-1][j]) else: dp[i][j] = dp[i-1][j] # for i in dp: # print(i) if dp[-1][-1] == sys.maxsize: return -1 return dp[-1][-1]
coin-change
Simple Python3 Solution Using Tabluar Method || DP
ajinkyabhalerao11
0
77
coin change
322
0.416
Medium
5,575
https://leetcode.com/problems/coin-change/discuss/2497234/Python-DP-Solution-(Memoization)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: d = {} def rec(index, sm): if sm == 0: return 0 if index < 0: return float('inf') else: take = float('inf') if coins[index] <= sm: if (index, sm-coins[index]) not in d: take = 1 + rec(index, sm-coins[index]) else: take = 1 + d[(index, sm-coins[index])] if (index-1, sm) not in d: notTake = rec(index-1, sm) else: notTake = d[(index-1, sm)] d[(index, sm)] = min(take, notTake) return d[(index, sm)] ans = rec(len(coins)-1, amount) if ans == float('inf'): return -1 else: return ans
coin-change
Python DP Solution (Memoization)
DietCoke777
0
66
coin change
322
0.416
Medium
5,576
https://leetcode.com/problems/coin-change/discuss/2402863/Python3-or-Looking-for-Feedback-Why-I'm-getting-TLE-for-Top-Down-Memoization!
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: #top down recursive approach! -> With Memoization dp! dp = [-1] * (amount + 1) coins.sort() def helper(amount): nonlocal coins nonlocal dp #add another base case for memo! if(dp[amount] != -1): return dp[amount] #base case if amount is 0! if(amount == 0): dp[amount] = 0 return 0 #is_possible is boolean flag indicating whether current amount is possible #to be added up using the coins array we are given as input! for coin in coins: remainder = amount - coin if(remainder >= 0): #check if dp[amount] == -1! If we don't already have an answer, #take the result of remainder by default1 if(dp[amount] == -1): dp[amount] = helper(remainder) else: dp[amount] = min(dp[amount], helper(remainder)) else: #break cause later coins will be also too large! break #once we solved all subproblems recursing from current problem, we found answer! return dp[amount] return helper(amount)
coin-change
Python3 | Looking for Feedback Why I'm getting TLE for Top-Down Memoization!
JOON1234
0
25
coin change
322
0.416
Medium
5,577
https://leetcode.com/problems/coin-change/discuss/2305121/Simple-Python-solution-with-DP-and-memoization
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # min number of coins summing up to current amount i memo = [-666]*(amount + 1) return self.dp(coins, amount, memo) def dp(self, coins, amount, memo): if (amount == 0): return 0 if (amount < 0): return -1 if (memo[amount] != -666): return memo[amount] res = sys.maxsize for coin in coins: subProblem = self.dp(coins, amount - coin, memo) if (subProblem == -1): continue res = min(subProblem + 1, res) memo[amount] = res if res != sys.maxsize else -1 return memo[amount]
coin-change
Simple Python solution with DP and memoization
leqinancy
0
44
coin change
322
0.416
Medium
5,578
https://leetcode.com/problems/wiggle-sort-ii/discuss/1322709/Definitely-not-O(n)-but-did-it-iteratively-in-O(nlog(N))-time
class Solution: def wiggleSort(self, nums: List[int]) -> None: sortedList = sorted(nums) n = len(nums) if n%2==0: small = sortedList[:((n//2))][::-1] large = (sortedList[(n//2):])[::-1] for i in range(1,n,2): nums[i] = large[i//2] for i in range(0,n,2): nums[i] = small[i//2] else: small = sortedList[:1+((n//2))][::-1] large = (sortedList[1+(n//2):])[::-1] for i in range(1,n,2): nums[i] = large[i//2] for i in range(0,n,2): nums[i] = small[i//2]
wiggle-sort-ii
Definitely not O(n) but did it iteratively in O(nlog(N)) time
prajwalPonnana004
1
180
wiggle sort ii
324
0.33
Medium
5,579
https://leetcode.com/problems/wiggle-sort-ii/discuss/2810053/Very-easy-solution-in-5-lines-using-python
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ tmp = nums.copy() tmp.sort() n = len(nums) i, j = 1, n - 1 for _ in range(2): for k in range(i, n, 2): # when i == 1 then gt elements and when i == 0 then sm elements with jump of 2 nums[k] = tmp[j] # sorted array tmp reverse order values assignment j -= 1 i -= 1
wiggle-sort-ii
Very easy solution in 5 lines using python
ankurbhambri
0
9
wiggle sort ii
324
0.33
Medium
5,580
https://leetcode.com/problems/wiggle-sort-ii/discuss/2123283/Python3-or-O(NLogN)-time-%2B-O(N)-Space
class Solution: def wiggleSort(self, nums: List[int]) -> None: if len(nums)>1: nums.sort() temp=nums[:] r=len(nums)-1 ind=1 while r>=0: nums[ind]=temp[r] ind+=2 if ind>=len(nums): ind=0 r-=1
wiggle-sort-ii
[Python3] | O(NLogN) time + O(N) Space
swapnilsingh421
0
105
wiggle sort ii
324
0.33
Medium
5,581
https://leetcode.com/problems/power-of-three/discuss/1179790/Simple-Python-Recursive-Solution-with-Explanation
class Solution: def isPowerOfThree(self, n: int) -> bool: if n == 1: return True if n == 0: return False else: return n % 3 == 0 and self.isPowerOfThree(n // 3)
power-of-three
Simple Python Recursive Solution with Explanation
stevenbooke
8
356
power of three
326
0.453
Easy
5,582
https://leetcode.com/problems/power-of-three/discuss/2470942/Python3-stupid-one-liner
class Solution: def isPowerOfThree(self, n: int) -> bool: return n in (1,3,9,27,81,243,729,2187,6561,19683,59049,177147,531441,1594323,4782969,14348907,43046721,129140163,387420489,1162261467)
power-of-three
Python3 stupid one-liner
leetavenger
4
558
power of three
326
0.453
Easy
5,583
https://leetcode.com/problems/power-of-three/discuss/2470942/Python3-stupid-one-liner
class Solution: def isPowerOfThree(self, n: int) -> bool: return n>=1 and log10(n)/log10(3)%1==0
power-of-three
Python3 stupid one-liner
leetavenger
4
558
power of three
326
0.453
Easy
5,584
https://leetcode.com/problems/power-of-three/discuss/2470942/Python3-stupid-one-liner
class Solution: def isPowerOfThree(self, n: int) -> bool: return n>=1 and 3**20%n==0
power-of-three
Python3 stupid one-liner
leetavenger
4
558
power of three
326
0.453
Easy
5,585
https://leetcode.com/problems/power-of-three/discuss/751445/Python3-a-few-approaches
class Solution: def isPowerOfThree(self, n: int) -> bool: if n <= 0: return False while n: n, r = divmod(n, 3) if n and r: return False return r == 1
power-of-three
[Python3] a few approaches
ye15
4
287
power of three
326
0.453
Easy
5,586
https://leetcode.com/problems/power-of-three/discuss/751445/Python3-a-few-approaches
class Solution: def isPowerOfThree(self, n: int) -> bool: return n > 0 and 3**(round(log(n)/log(3))) == n
power-of-three
[Python3] a few approaches
ye15
4
287
power of three
326
0.453
Easy
5,587
https://leetcode.com/problems/power-of-three/discuss/751445/Python3-a-few-approaches
class Solution: def isPowerOfThree(self, n: int) -> bool: return n > 0 and 3**19 % n == 0
power-of-three
[Python3] a few approaches
ye15
4
287
power of three
326
0.453
Easy
5,588
https://leetcode.com/problems/power-of-three/discuss/751445/Python3-a-few-approaches
class Solution: def isPowerOfThree(self, n: int) -> bool: if n <= 0: return False while n > 1: n, x = divmod(n, 3) if x > 0: return False return True
power-of-three
[Python3] a few approaches
ye15
4
287
power of three
326
0.453
Easy
5,589
https://leetcode.com/problems/power-of-three/discuss/406575/Python-Beats-95
class Solution: def isPowerOfThree(self, n: int) -> bool: if n==0: return False while (n%3==0): n /=3 if n==1: return True return False
power-of-three
Python Beats 95%
saffi
3
991
power of three
326
0.453
Easy
5,590
https://leetcode.com/problems/power-of-three/discuss/2345734/Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Math
class Solution: def isPowerOfThree(self, n: int) -> bool: if n < 1: return False # if the number is zero or in negative. if n == 1: return True # 1 could be a power of any number. while n > 1: # now will check for the number greater then 1. if n % 3 != 0: # if the provided number is not a perfect division of 3, then its can be a power of 3. return False # if not n /= 3 #n = n / 3 # to update n for further division. This loop will run 3 times in case of perfect division &amp; n value will be updated 3 times(9,3,0.43) return True
power-of-three
Python Simplest Solution With Explanation | Beg to adv | Math
rlakshay14
2
173
power of three
326
0.453
Easy
5,591
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): m, x = 0, 0 while m < n: m = 3**x x += 1 return n > 0 and n == m
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,592
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): if n == 0: return False while not n % 3: n //= 3 return n == 1
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,593
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): if n % 3: return n == 1 return n > 0 and self.isPowerOfThree(n//3)
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,594
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): return n > 0 and n == 3**round(math.log(n,3),9)
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,595
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): return n > 0 and float.is_integer(round(math.log(n,3),9))
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,596
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): powersOfThree = [1] while powersOfThree[-1] < 2**31-1: powersOfThree.append(3 * powersOfThree[-1]) return n in powersOfThree
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,597
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): return n in map(lambda x : 3**x, range(0,20))
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,598
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions
class Solution: def isPowerOfThree(self, n): return n in [3**x for x in range(0,20)]
power-of-three
Python - Clean and Simple! Multiple Solutions
domthedeveloper
2
210
power of three
326
0.453
Easy
5,599