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/guess-number-higher-or-lower-ii/discuss/2273592/Python3-oror-dp-binSearch-w-explanation-oror-TM%3A-96-47
class Solution: def getMoneyAmount(self, n): # For an interval [l,r], we choose a num, which if incorrect still # allows us to know whether the secret# is in either [l,num-1] or # [num+1,r]. So, the worst-case (w-c) cost is # # num + max(w-c cost in [l,num-1], w-c cost in [num+1,r]) # # We do this by recursion and binary search, starting with [1,n]. @lru_cache(None) # <-- we cache function results to avoid recomputing them def dp(l = 1, r = n)-> int: if r-l < 1: return 0 # <-- base case for the recursion; one number in [l,r] ans = 1000 # <-- the answer for n = 200 is 952 for choice in range((l+r)//2,r): ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r))) return ans return dp()
guess-number-higher-or-lower-ii
Python3 || dp, binSearch w/ explanation || T/M: 96%/ 47%
warrenruud
2
171
guess number higher or lower ii
375
0.465
Medium
6,400
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/2053913/Python-easy-to-read-and-understand-or-recusion-%2B-memoization
class Solution: def solve(self, start, end): if start >= end: return 0 if (start, end) in self.d: return self.d[(start, end)] self.d[(start, end)] = float("inf") for i in range(start, end+1): cost1 = self.solve(start, i-1) + i cost2 = self.solve(i+1, end) + i cost = max(cost1, cost2) self.d[(start, end)] = min(self.d[(start, end)], cost) return self.d[(start, end)] def getMoneyAmount(self, n: int) -> int: self.d = {} return self.solve(1, n)
guess-number-higher-or-lower-ii
Python easy to read and understand | recusion + memoization
sanial2001
1
233
guess number higher or lower ii
375
0.465
Medium
6,401
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/1416152/Python3-DP-solution-time-beats-70-space-beats-88
class Solution: def getMoneyAmount(self, n: int) -> int: dp = [[0] * (n + 1) for _ in range(n + 1)] for length in range(2, n + 1): for left in range(1, n - length + 2): right = left + length - 1 dp[left][right] = float('inf') for k in range(left + 1, right): dp[left][right] = min(dp[left][right], max(dp[left][k - 1], dp[k + 1][right]) + k) if left + 1 = right: dp[left][left + 1] = left return dp[1][n] #the idea of my solution is to find the best case in worst case. what does it mean? #we know the big interval relys on small interval, so we will only study the smallest case #if the interval is 0, dp[i][i] what is the value of this interval? it has to be 0, because you dont need to guess #what if the interval is 2, impossible to have interval 1, interval is 2 the value should be the smaller number #lets look at this example: [1,2] [2,3] you definatly gonna pick the cheap one, because after you pick one the answer #will be the another. #because all the even interval will rely on the dp of interval 2, so once the dp[i][i + 1] is solved, the whole problem is solved !
guess-number-higher-or-lower-ii
Python3, DP solution, time beats 70%, space beats 88%
AustinLau
1
333
guess number higher or lower ii
375
0.465
Medium
6,402
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/813676/Python3-top-down-dp
class Solution: def getMoneyAmount(self, n: int) -> int: @lru_cache(None) def fn(lo, hi): """The cost of guessing a number where lo <= x <= hi.""" if lo >= hi: return 0 # no need to guess ans = inf for mid in range(lo, hi+1): ans = min(ans, mid + max(fn(lo, mid-1), fn(mid+1, hi))) return ans return fn(1, n)
guess-number-higher-or-lower-ii
[Python3] top-down dp
ye15
1
202
guess number higher or lower ii
375
0.465
Medium
6,403
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/2842707/python-solution-Guess-Number-Higher-or-Lower-II
class Solution: def getMoneyAmount(self, n: int) -> int: dp = [[0 for i in range(n+2)] for j in range(n+2)] for start in range(n,0,-1): for end in range(start,n+1): if start == end: continue else: ans = float('inf') for i in range(start,end+1): ans = min(ans, i + max(dp[start][i-1],dp[i+1][end] )) dp[start][end] = ans return dp[1][n]
guess-number-higher-or-lower-ii
python solution Guess Number Higher or Lower II
sarthakchawande14
0
2
guess number higher or lower ii
375
0.465
Medium
6,404
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/1190265/python-or-dp
class Solution: def getMoneyAmount(self, n: int) -> int: new=[[0 for i in range(0,n+1)] for i in range(0,n+1)] for gap in range(1,n+1): for j in range(gap,n+1): i=j-gap if gap==1: new[i][j]=min(i,j) continue if i==0 or j==0: continue mini=8765432 for k in range(i,j+1): if k==i: ans=i+new[i+1][j] elif k==j: ans=j+new[i][j-1] else: ans=k+max(new[k+1][j],new[i][k-1]) mini=min(ans,mini) new[i][j]=mini print(new) return new[1][-1]
guess-number-higher-or-lower-ii
python | dp
heisenbarg
0
228
guess number higher or lower ii
375
0.465
Medium
6,405
https://leetcode.com/problems/wiggle-subsequence/discuss/2230152/Beats-73.3-Simple-Python-Solution-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: length = 0 curr = 0 for i in range(len(nums) - 1): if curr == 0 and nums[i + 1] - nums[i] != 0: length += 1 curr = nums[i + 1] - nums[i] if curr < 0 and nums[i + 1] - nums[i] > 0: length += 1 curr = nums[i + 1] - nums[i] elif curr > 0 and nums[i + 1] - nums[i] < 0: length += 1 curr = nums[i + 1] - nums[i] else: continue return length + 1
wiggle-subsequence
Beats 73.3% - Simple Python Solution - Greedy
7yler
3
183
wiggle subsequence
376
0.482
Medium
6,406
https://leetcode.com/problems/wiggle-subsequence/discuss/1406220/Python-3-oror-Dynamicprogramming-oror-recursion-%2B-memoization-oror-self-explanatory
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: memo={} def recurse(index,state): if index==len(nums): return 0 if index in memo: return memo[index] ans=1 for i in range(index+1,len(nums)): if state=='positive' and nums[i]-nums[index]<0: ans=max(ans,1+recurse(i,'negative')) elif state=='negative'and nums[i]-nums[index]>0: ans=max(ans,1+recurse(i,'positive')) memo[index]=ans return memo[index] res=float('-inf') for i in range(1,len(nums)): if nums[i]-nums[i-1]>0: res=max(res,1+recurse(i,'positive')) elif nums[i]-nums[i-1]<0: res=max(res,1+recurse(i,'negative')) if res==float('-inf'): return 1 return res
wiggle-subsequence
Python 3 || Dynamicprogramming || recursion + memoization || self-explanatory
bug_buster
3
305
wiggle subsequence
376
0.482
Medium
6,407
https://leetcode.com/problems/wiggle-subsequence/discuss/2231991/Python3-solution-using-DP-top-down-approach
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: dp = {} result = [0] def getSign(diff): if diff < 0: return "N" if diff > 0: return "P" return "E" def getResult(index,sign): if index >= len(nums) - 1: return 1 if index in dp: return dp[index] consider = 0 dontConsider = 0 x = getSign(nums[index] - nums[index+1]) if not sign and x!="E": consider = 1 + getResult(index+1, x) elif sign == "P" and x == "N": consider = 1 + getResult(index+1, x) elif sign == "N" and x == "P": consider = 1 + getResult(index+1, x) dontConsider = getResult(index+1,sign) dp[index] = max(consider, dontConsider) result[0] = max(result[0], dp[index]) return dp[index] getResult(0,"") if result[0] == 0 and len(dp)==0: return len(nums) return result[0]
wiggle-subsequence
📌 Python3 solution using DP top down approach
Dark_wolf_jss
2
26
wiggle subsequence
376
0.482
Medium
6,408
https://leetcode.com/problems/wiggle-subsequence/discuss/2715354/Stack-O(n)-Time-Solution
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: flag = 1 stack = [nums[0]] i = 1 while i < len(nums) and nums[i] == nums[i-1]: i += 1 if i < len(nums): if nums[i-1] > nums[i]: flag = -1 stack.append(nums[i]) for num in nums[i+1:]: if num == stack[-1]: continue if flag == 1: # Increasing if num > stack[-1]: stack.pop() else: flag *= -1 else: # flag = -1 => Decreasing if num < stack[-1]: stack.pop() else: flag *= -1 stack.append(num) return len(stack)
wiggle-subsequence
Stack O(n) Time Solution ✅
samirpaul1
1
62
wiggle subsequence
376
0.482
Medium
6,409
https://leetcode.com/problems/wiggle-subsequence/discuss/2274937/Python-or-O(N)-or-Dynamic-Programming-or-Simple-and-easy-explanation
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: #create 2 lists to capture positive and negative wiggle sequences pos = [1 for _ in range(len(nums))] neg = [1 for _ in range(len(nums))] for i in range(1,len(nums)): # if the current number is > previous, we add 1 to the last occurence of negative sequence # and store it as a positive sequence if nums[i]>nums[i-1]: pos[i] = neg[i-1]+1 neg[i] = neg[i-1] # if the current number is < previous, we add 1 to the last occurence of positive sequence # and store it as a negative sequence elif nums[i]<nums[i-1]: neg[i] = pos[i-1]+1 pos[i] = pos[i-1] # else we just keep copy the previous sequence until a positive or negative sequence occurs else: neg[i] = neg[i-1] pos[i] = pos[i-1] #max wiggle subsequence can either come from positive sequence or negative sequence return max(pos[-1],neg[-1])
wiggle-subsequence
Python | O(N) | Dynamic Programming | Simple and easy explanation
vishyarjun1991
1
54
wiggle subsequence
376
0.482
Medium
6,410
https://leetcode.com/problems/wiggle-subsequence/discuss/2232131/very-easy-python-solution-(39-ms-faster-than-86.63)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: inc = 1 dec = 1 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: inc = dec + 1 elif nums[i] < nums[i-1]: dec = inc + 1 return max(inc, dec)
wiggle-subsequence
very easy python solution (39 ms, faster than 86.63%)
hamza94
1
31
wiggle subsequence
376
0.482
Medium
6,411
https://leetcode.com/problems/wiggle-subsequence/discuss/2229719/WEEB-DOES-PYTHONC%2B%2B-DP-(2-METHODS)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: dp = [0 for i in range(len(nums)-1)] isPositive = False for i in range(len(nums)-1): if nums[i+1] - nums[i] > 0 and not isPositive: isPositive = True dp[i] = dp[i-1] + 1 elif nums[i+1] - nums[i] > 0 and isPositive: dp[i] = dp[i-1] elif nums[i+1] - nums[i] < 0 and not isPositive: if dp[i-1] == 0: dp[i] = dp[i-1] + 1 else: dp[i] = dp[i-1] elif nums[i+1] - nums[i] < 0 and isPositive: isPositive = False dp[i] = dp[i-1] + 1 else: # nums[i+1] - nums[i] == 0 dp[i] = dp[i-1] return dp[-1] + 1 if len(nums)>1 else 1
wiggle-subsequence
WEEB DOES PYTHON/C++ DP (2 METHODS)
Skywalker5423
1
75
wiggle subsequence
376
0.482
Medium
6,412
https://leetcode.com/problems/wiggle-subsequence/discuss/2229719/WEEB-DOES-PYTHONC%2B%2B-DP-(2-METHODS)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: result = 0 isPositive = False for i in range(len(nums)-1): if nums[i+1] - nums[i] > 0 and not isPositive: isPositive = True result += 1 elif nums[i+1] - nums[i] < 0 and not isPositive: if result == 0: result += 1 elif nums[i+1] - nums[i] < 0 and isPositive: isPositive = False result += 1 return result + 1
wiggle-subsequence
WEEB DOES PYTHON/C++ DP (2 METHODS)
Skywalker5423
1
75
wiggle subsequence
376
0.482
Medium
6,413
https://leetcode.com/problems/wiggle-subsequence/discuss/2738520/DP-oror-91.97-Faster-oror-Memoization-oror-Tabulation-oror-Space-Optimization
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) # SPACE OPTIMIZATION next_row = [0 for j in range(2)] curr_row = [0 for j in range(2)] for index in range(n-2, -1, -1): curr_row = [0 for j in range(2)] for lastSign in range(2): if lastSign == 1: ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] < 0: ans1 = 1+next_row[0] ans2 = next_row[lastSign] curr_row[1] = max(ans1, ans2) elif lastSign == 0: ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] > 0: ans1 = 1+next_row[1] ans2 = next_row[lastSign] curr_row[0] = max(ans1, ans2) next_row = curr_row return 1+max(curr_row) # TABULATION dp = [[-1 for j in range(2)] for i in range(n)] dp[n-1][0] = 0 dp[n-1][1] = 0 for index in range(n-2, -1, -1): for lastSign in range(2): if lastSign == 1: ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] < 0: ans1 = 1+dp[index+1][0] ans2 = dp[index+1][lastSign] dp[index][1] = max(ans1, ans2) elif lastSign == 0: ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] > 0: ans1 = 1+dp[index+1][1] ans2 = dp[index+1][lastSign] dp[index][0] = max(ans1, ans2) return 1+max(dp[0]) # MEMOIZATION def helper(index, lastSign): nonlocal n if index+1 == n: return 0 ans1 = 0 ans2 = 0 if lastSign == 'pos': if dp[index][1] != -1: return dp[index][1] else: if dp[index][0] != -1: return dp[index][0] if lastSign == 'pos': ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] < 0: ans1 = 1+helper(index+1, 'neg') ans2 = helper(index+1, lastSign) dp[index][1] = max(ans1, ans2) return max(ans1, ans2) elif lastSign == 'neg': ans1 = 0 ans2 = 0 if nums[index]-nums[index+1] > 0: ans1 = 1+helper(index+1, 'pos') ans2 = helper(index+1, lastSign) dp[index][0] = max(ans1, ans2) return max(ans1,ans2) return 1 + max(helper(0, 'pos'), helper(0, 'neg'))
wiggle-subsequence
DP || 91.97% Faster || Memoization || Tabulation || Space Optimization
shreya_pattewar
0
12
wiggle subsequence
376
0.482
Medium
6,414
https://leetcode.com/problems/wiggle-subsequence/discuss/2519979/Python-95-faster
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: dp = [nums[i+1]-nums[i] for i in range(len(nums)-1) if nums[i]!=nums[i+1]] if not dp: return 1 cur = 2 # base case for i in range(len(dp)-1): if dp[i]>0 and dp[i+1]<0 or dp[i]<0 and dp[i+1]>0: cur+=1 return cur
wiggle-subsequence
Python 95 % faster
Abhi_009
0
97
wiggle subsequence
376
0.482
Medium
6,415
https://leetcode.com/problems/wiggle-subsequence/discuss/2328275/Python-Simple-Faster-than-89.45-O(n)-oror-Documented
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: diffs = [] # calculate differences excluind zeros for i in range(1, len(nums)): diff = nums[i-1]-nums[i] if diff != 0: diffs.append(diff) # if diff is empty means, minimum 1 sub-sequence exist because 1 <= nums.length if not diffs: return 1 # traverse the differcens, starting from 2nd element count = 2 for i in range(1, len(diffs)): if (diffs[i-1]>0 and diffs[i]<0) or (diffs[i]>0 and diffs[i-1]<0): count += 1 # return the result return count
wiggle-subsequence
[Python] Simple Faster than 89.45% - O(n) || Documented
Buntynara
0
13
wiggle subsequence
376
0.482
Medium
6,416
https://leetcode.com/problems/wiggle-subsequence/discuss/2233543/Python-solution-or-Wiggle-Subsequence
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if(len(nums) < 2): return len(nums) prevDiff = nums[1] - nums[0] if prevDiff != 0: count = 2 else: count = 1 for i in range(2,len(nums)): diff = nums[i] - nums[i-1] if (prevDiff >= 0 and diff < 0) or (prevDiff <= 0 and diff > 0): count += 1 prevDiff = diff return count
wiggle-subsequence
Python solution | Wiggle Subsequence
nishanrahman1994
0
4
wiggle subsequence
376
0.482
Medium
6,417
https://leetcode.com/problems/wiggle-subsequence/discuss/2233539/Easy-to-understand-O-(N)-Python
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: longest_substring_ending_downwards = 1 longest_substring_ending_upwards = 1 for prev, curr in zip(nums, nums[1:]): if prev > curr: longest_substring_ending_downwards = longest_substring_ending_upwards + 1 elif prev < curr: longest_substring_ending_upwards = longest_substring_ending_downwards + 1 return max(longest_substring_ending_downwards, longest_substring_ending_upwards)
wiggle-subsequence
Easy to understand O (N) Python
christianantonyquero
0
35
wiggle subsequence
376
0.482
Medium
6,418
https://leetcode.com/problems/wiggle-subsequence/discuss/2233095/Simple-Python-Solution
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if len(nums) ==1 or max(nums) == 0 : return 1 uni_list=[] for num in nums: if num not in uni_list: uni_list.append(num) last = uni_list[1] - uni_list[0] current = 0 li=[uni_list[0], uni_list[1]] for i in range(1, len(nums)): current = nums[i] - nums[i-1] if current * last < 0: li.append(nums[i]) last = current return len(li)
wiggle-subsequence
Simple Python Solution
salsabilelgharably
0
9
wiggle subsequence
376
0.482
Medium
6,419
https://leetcode.com/problems/wiggle-subsequence/discuss/2232363/Python-Recursive-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: # Get the maximum length provided when starting difference was either negative or positive return max(self.helper(nums, 0, False), self.helper(nums, 0, True)) def helper(self, nums, index, isPrevPositive): # If at last element, only one element is left, return 1 as maxLength wiggle if index >= len(nums) - 1: return 1 output1 = float("-inf") output2 = float("-inf") # If previous difference was positive if isPrevPositive: # If previous was positive, wiggle is only possible if next element is less than # current, so that difference can be negative # if next element is less than current element, # take that element, and increase the wiggle if nums[index + 1] < nums[index]: output1 = 1 + self.helper(nums, index + 1, False) else: # Don't take the element output1 = self.helper(nums, index + 1, isPrevPositive) # If previous difference was negative else: # Same as above, next element should be greater than current to make it wiggle if nums[index + 1] > nums[index]: output2 = 1 + self.helper(nums, index + 1, True) # else leave the element else: output2 = self.helper(nums, index + 1, isPrevPositive) # return the max length of wiggle from both cases return max(output1, output2)
wiggle-subsequence
Python Recursive + Memoization + DP + Greedy
zippysphinx
0
30
wiggle subsequence
376
0.482
Medium
6,420
https://leetcode.com/problems/wiggle-subsequence/discuss/2232363/Python-Recursive-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: memo = [-1 for _ in range(len(nums) + 1)] return max(self.helper(nums, 0, False, memo.copy()), self.helper(nums, 0, True, memo.copy())) def helper(self, nums, index, isPrevPositive, memo): if index >= len(nums) - 1: return 1 if memo[index] != -1: return memo[index] output1 = float("-inf") output2 = float("-inf") if isPrevPositive: if nums[index + 1] < nums[index]: output1 = 1 + self.helper(nums, index + 1, False, memo) else: output1 = self.helper(nums, index + 1, isPrevPositive, memo) else: if nums[index + 1] > nums[index]: output2 = 1 + self.helper(nums, index + 1, True, memo) else: output2 = self.helper(nums, index + 1, isPrevPositive, memo) memo[index] = max(output1, output2) return memo[index]
wiggle-subsequence
Python Recursive + Memoization + DP + Greedy
zippysphinx
0
30
wiggle subsequence
376
0.482
Medium
6,421
https://leetcode.com/problems/wiggle-subsequence/discuss/2232363/Python-Recursive-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) # For Single element, maxLength = 1 up = 1 down = 1 for i in range(1, len(nums)): # Now, If this element is smaller than previous, # means it is a down element, therefore # Down will be incremented, # SO we will make down = 1 + maxLength of "UP" upto that element # because for this to be down and considered, previous should be "UP" element if nums[i] < nums[i - 1]: down = up + 1 # Same case for the element greater than previous element elif nums[i] > nums[i - 1]: up = down + 1 return max(up, down)
wiggle-subsequence
Python Recursive + Memoization + DP + Greedy
zippysphinx
0
30
wiggle subsequence
376
0.482
Medium
6,422
https://leetcode.com/problems/wiggle-subsequence/discuss/2232363/Python-Recursive-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) if n < 2: return n # calculate the first difference prevDiff = nums[1] - nums[0] # increase count, if first difference !- 0 else 1 count = 2 if prevDiff != 0 else 1 # Calculate other differences for i in range(2, n): diff = nums[i] - nums[i - 1] # Only increase count when you have successfult combo # if current difference is negative then previous must me positive # if current difference is positive then previous must me negative if (diff < 0 and prevDiff >= 0) or (diff > 0 and prevDiff <= 0): count += 1 # Now, swap the current diff with prev difference prevDiff = diff return count
wiggle-subsequence
Python Recursive + Memoization + DP + Greedy
zippysphinx
0
30
wiggle subsequence
376
0.482
Medium
6,423
https://leetcode.com/problems/wiggle-subsequence/discuss/2232076/Greedy-Approach-oror-Clean-Code
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if len(nums) == 1: return 1 increasing = 1 decreasing = 1 n = len(nums) for i in range(1, n): if nums[i] > nums[i - 1]: increasing = decreasing + 1 elif nums[i] < nums[i - 1]: decreasing = increasing + 1 return max(increasing, decreasing)
wiggle-subsequence
Greedy Approach || Clean Code
Vaibhav7860
0
11
wiggle subsequence
376
0.482
Medium
6,424
https://leetcode.com/problems/wiggle-subsequence/discuss/2231514/GolangGoPython-O(N)-Solution
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: idx = 1 while idx < len(nums) and nums[idx-1] == nums[idx]: idx+=1 if idx == len(nums): return 1 up = nums[idx-1] < nums[idx] counter = 2 for i in range(1,len(nums)): if (up and nums[i-1] > nums[i]) or (not up and nums[i-1] < nums[i]): counter+=1 up = not up return counter
wiggle-subsequence
Golang/Go/Python O(N) Solution
vtalantsev
0
6
wiggle subsequence
376
0.482
Medium
6,425
https://leetcode.com/problems/wiggle-subsequence/discuss/2231248/Python3-O(n)-Iterative-Greedy
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if len(nums) == 0: return 0 elif len(nums) == 1: return 1 l_neg = 1 # Maximum length of wiggle starting with negative diff c_neg = nums[0] # Current number for wiggle starting with negative diff b_neg = True # True = looking for numbers smaller than c_neg. False = looking for numbers larger than c_neg l_pos = 1 # Maximum length of wiggle starting with positive diff c_pos = nums[0] # Current number for wiggle starting with positive diff b_pos = True # True = looking for numbers greater than c_pos. False = looking for numbers smaller than c_pos for i in range(1, len(nums)): if nums[i] > c_pos: if b_pos == True: c_pos = nums[i] l_pos += 1 b_pos = False else: c_pos = nums[i] # Take larger number, since it will be more likely to find smaller numbers later elif nums[i] < c_pos: if b_pos == False: c_pos = nums[i] l_pos += 1 b_pos = True else: c_pos = nums[i] # Take smaller number, since it will be more likely to find larger numbers later if nums[i] < c_neg: if b_neg == True: c_neg = nums[i] l_neg += 1 b_neg = False else: c_neg = nums[i] # Take smaller number, since it will be more likely to find larger numbers later elif nums[i] > c_neg: if b_neg == False: c_neg = nums[i] l_neg += 1 b_neg = True else: c_neg = nums[i] # Take larger number, since it will be more likely to find smaller numbers later return max(l_neg, l_pos)
wiggle-subsequence
[Python3] O(n) Iterative Greedy
betaRobin
0
5
wiggle subsequence
376
0.482
Medium
6,426
https://leetcode.com/problems/wiggle-subsequence/discuss/2231068/Python3-Solution-with-using-dp
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: up, down = 0, 0 for i in range(len(nums) - 1): if nums[i] < nums[i + 1]: up = down + 1 elif nums[i] > nums[i + 1]: down = up + 1 return max(up, down) + 1
wiggle-subsequence
[Python3] Solution with using dp
maosipov11
0
7
wiggle subsequence
376
0.482
Medium
6,427
https://leetcode.com/problems/wiggle-subsequence/discuss/2230722/376.-Wiggle-Subsequence
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: ans=[] if len(nums)<2 or len(set(nums))<2: return len(set(nums)) def isalt(nums): dp=[1 for j in range(len(nums)+1)] for i in range(0,len(nums)): for j in range(0,i): if nums[i]>0 and nums[j]<0: dp[i]=max(dp[i],dp[j]+1) elif nums[i]<0 and nums[j]>0: dp[i]=max(dp[i],dp[j]+1) return max(dp)+1 for i in range(len(nums)-1): ans.append(nums[i+1]-nums[i]) return isalt(ans)
wiggle-subsequence
376. Wiggle Subsequence
Revanth_Yanduru
0
7
wiggle subsequence
376
0.482
Medium
6,428
https://leetcode.com/problems/wiggle-subsequence/discuss/2230053/Python-Simple-Python-Solution
class Solution: def wiggleMaxLength(self, nums): l, h = 1, 1 for i in range(1, len(nums)): if nums[i-1] < nums[i]: h = l + 1 elif nums[i-1] > nums[i]: l = h + 1 return max(l,h)
wiggle-subsequence
[ Python ]✔✔ Simple Python Solution ✔✔✔
vaibhav0077
0
20
wiggle subsequence
376
0.482
Medium
6,429
https://leetcode.com/problems/wiggle-subsequence/discuss/2229635/DP-python3
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if len(nums) < 2: return len(nums) down = 1 up = 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: up = down +1 elif nums[i] < nums[i-1]: down = up + 1 return max(down, up) ```
wiggle-subsequence
DP python3
hilda8519
0
9
wiggle subsequence
376
0.482
Medium
6,430
https://leetcode.com/problems/wiggle-subsequence/discuss/1618199/Python3-Greedy-Solution-oror-TIME-O(N)-SPACE-O(1)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) if n <= 1: return n count = 1 i = 1 while i < n and nums[i] == nums[i-1]: i+=1 if i == n: return count prevDiff = nums[i]-nums[i-1] while i < n: if nums[i] == nums[i-1]: i+=1 continue else: currDiff = nums[i] - nums[i-1] if currDiff * prevDiff < 0: count +=1 prevDiff = currDiff i+=1 continue return count+1
wiggle-subsequence
Python3 Greedy Solution || TIME O(N), SPACE O(1)
henriducard
0
61
wiggle subsequence
376
0.482
Medium
6,431
https://leetcode.com/problems/wiggle-subsequence/discuss/1585932/100-efficient-Simple-Code-(Python3)%3A-O(n)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n=len(nums) ar=[] ar.append(nums[0]) for i in range(1,n): if i==1 or len(ar)==1: if nums[i] > ar[0] or nums[i] < ar[0]: ar.append(nums[i]) else: pass else: if(nums[i]>ar[-1] ): if (ar[-1]>=ar[-2]): ar[-1]=nums[i] else: ar.append(nums[i]) else: if(nums[i]==ar[-1]): continue if (ar[-1]<=ar[-2]): ar[-1]=nums[i] else: ar.append(nums[i]) return len(ar)
wiggle-subsequence
100% efficient Simple Code (Python3): O(n)
martian_rock
0
112
wiggle subsequence
376
0.482
Medium
6,432
https://leetcode.com/problems/wiggle-subsequence/discuss/1364112/Simple-Easy-Python-solution-with-diagram-Explaination-or-O(n)-time-and-O(1)-space
class Solution: def isValley(self, li, i, n): if i-1>=0 and i+1 < n: return li[i-1] > li[i] <= li[i+1] elif i-1>=0: return li[i-1] > li[i] elif i+1 <n: return li[i] <= li[i+1] return True def isPeak(self, li, i, n): if i-1>=0 and i+1 < n: return li[i-1] < li[i] >= li[i+1] elif i-1>=0: return li[i-1] < li[i] elif i+1 <n: return li[i] >= li[i+1] return True def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) li = [nums[0]] for i in range(1, n): if nums[i] != li[-1]: li.append(nums[i]) n = len(li) cnt = 1 for i in range(1, n): if self.isValley(li, i, n) or self.isPeak(li, i, n): cnt+=1 return cnt
wiggle-subsequence
Simple Easy Python solution with diagram Explaination | O(n) time and O(1) space
sathwickreddy
0
60
wiggle subsequence
376
0.482
Medium
6,433
https://leetcode.com/problems/wiggle-subsequence/discuss/1116147/Python-Simple-solution.-No-dp
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: total = 1 prev = None for n1, n2 in zip(nums, nums[1:]): if n1 == n2: continue cur = n1 < n2 total += (prev != cur) prev = cur return total
wiggle-subsequence
[Python] Simple solution. No dp
JummyEgg
0
34
wiggle subsequence
376
0.482
Medium
6,434
https://leetcode.com/problems/wiggle-subsequence/discuss/817530/Python3-count-extrema
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: ans = 1 prev = 0 for i in range(1, len(nums)): diff = nums[i] - nums[i-1] if diff: if prev*diff <= 0: ans += 1 prev = diff return ans
wiggle-subsequence
[Python3] count extrema
ye15
0
55
wiggle subsequence
376
0.482
Medium
6,435
https://leetcode.com/problems/wiggle-subsequence/discuss/514071/Python3-simple-solution-faster-than-99.62
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if len(nums)<2: return len(nums) diffs=[] for i in range(1,len(nums)): if nums[i] - nums[i-1] !=0: diffs.append(nums[i]-nums[i-1]) if not diffs: return 1 count=2 for i in range(1,len(diffs)): if (diffs[i]*diffs[i-1])<0: count+=1 return count
wiggle-subsequence
Python3 simple solution faster than 99.62%
jb07
0
61
wiggle subsequence
376
0.482
Medium
6,436
https://leetcode.com/problems/wiggle-subsequence/discuss/1019353/Python-Dynamic-Programming-Approach
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if not nums: return 0 less = [1]*len(nums) more = [1]*len(nums) res_l = 1 res_m = 1 for i in range(1,len(nums)): for j in range(i): if nums[i] > nums[j] and more[i] < less[j]+1: more[i] = less[j]+1 res_m = more[i] elif nums[i] < nums[j] and less[i] < more[j]+1: less[i] = more[j]+1 res_l = less[i] return max(res_l,res_m)
wiggle-subsequence
Python Dynamic Programming Approach
tgoel219
-1
90
wiggle subsequence
376
0.482
Medium
6,437
https://leetcode.com/problems/combination-sum-iv/discuss/1272869/Python-3-Faster-than-96-(Super-Simple!)
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: waysToAdd = [0 for x in range(target+1)] waysToAdd[0] = 1 for i in range(min(nums), target+1): waysToAdd[i] = sum(waysToAdd[i-num] for num in nums if i-num >= 0) return waysToAdd[-1]
combination-sum-iv
[Python 3] Faster than 96% (Super Simple!)
jodoko
3
323
combination sum iv
377
0.521
Medium
6,438
https://leetcode.com/problems/combination-sum-iv/discuss/2383087/Python3-or-DP-or-Top-Down
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = defaultdict(int) return self.rec(nums, target, dp) def rec(self, nums, target, dp): if target == 0: return 1 if target < 0: return 0 if target in dp: return dp[target] for num in nums: dp[target] += self.rec(nums, target-num, dp) return dp[target]
combination-sum-iv
Python3 | DP | Top Down
khaydaraliev99
1
65
combination sum iv
377
0.521
Medium
6,439
https://leetcode.com/problems/combination-sum-iv/discuss/2382243/Two-solutions-using-dp-and-caching-in-Python
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: ''' Here we are doing bottom up DP and the base case would be => when target is zero how many way can we achieve that: 1 way ''' dp = { 0 : 1 } # base case for total in range(1,target+1): dp[total] = 0 for n in nums: dp[total] += dp.get(total-n,0) return dp[target] # /////// Solution 1 /////// def combinations(self, nums, target, combination, lookup): if target == 0: return 1 if target < 0: return 0 if target not in lookup: ans = 0 for num in nums: ans += self.combinations(nums, target-num, combination+[num], lookup) lookup[target] = ans return lookup[target] def combinationSum4(self, nums: List[int], target: int) -> int: nums.sort() return self.combinations(nums, target, [], {})
combination-sum-iv
Two solutions using dp and caching in Python
__Asrar
1
23
combination sum iv
377
0.521
Medium
6,440
https://leetcode.com/problems/combination-sum-iv/discuss/2295228/Python-90-faster
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = {} def solve(nums, target, asf): if asf in dp: return dp[asf] if asf<0: return 0 if asf == 0: return 1 ans = 0 for i in nums: ans += solve(nums, target, asf-i) dp[asf] = ans return ans return solve(nums,target,target)
combination-sum-iv
Python 90% faster
Abhi_009
1
101
combination sum iv
377
0.521
Medium
6,441
https://leetcode.com/problems/combination-sum-iv/discuss/738256/Python3-dp-(top-down-and-bottom-up)
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @cache def fn(n): """Return number of combinations adding up to n.""" if n <= 0: return int(n == 0) return sum(fn(n - x) for x in nums) return fn(target)
combination-sum-iv
[Python3] dp (top-down & bottom-up)
ye15
1
241
combination sum iv
377
0.521
Medium
6,442
https://leetcode.com/problems/combination-sum-iv/discuss/738256/Python3-dp-(top-down-and-bottom-up)
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0]*(target + 1) dp[0] = 1 for i in range(target): if dp[i]: for x in nums: if i+x <= target: dp[i+x] += dp[i] return dp[-1]
combination-sum-iv
[Python3] dp (top-down & bottom-up)
ye15
1
241
combination sum iv
377
0.521
Medium
6,443
https://leetcode.com/problems/combination-sum-iv/discuss/2656605/Simple-1D-Bottom-up-DP
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target+1) dp[-1] = 1 # base case for amt in range(target, -1, -1): for n in nums: if amt + n <= target: dp[amt] += dp[amt+n] return dp[0]
combination-sum-iv
Simple 1D Bottom-up DP
jonathanbrophy47
0
8
combination sum iv
377
0.521
Medium
6,444
https://leetcode.com/problems/combination-sum-iv/discuss/2438049/Bottom-Up-Python-Faster-than-80
class Solution(object): def combinationSum4(self, nums, target): dp=[1]+[0]*target # print(dp) for i in range(1,target+1): for j in range(len(nums)): if i-nums[j]>=0: dp[i]+=dp[i-nums[j]] return dp[target]
combination-sum-iv
Bottom Up Python Faster than 80%
Prithiviraj1927
0
54
combination sum iv
377
0.521
Medium
6,445
https://leetcode.com/problems/combination-sum-iv/discuss/2438019/Memoization-Top-Down-Approach-Python-Faster-than-90
# class Solution: class Solution(object): def combinationSum4(self, nums, target): dp=[-1]*target def rec(j): # print(j,dp) if j>target: return 0 if j==target: return 1 if dp[j]!=-1: return dp[j] # dp[j]=0 su=0 for i in range(len(nums)): su+=rec(nums[i]+j) dp[j]=su # print(dp) return dp[j] # dp[j]=su # print(dp) return rec(0)
combination-sum-iv
Memoization - Top Down Approach Python - Faster than 90%
Prithiviraj1927
0
45
combination sum iv
377
0.521
Medium
6,446
https://leetcode.com/problems/combination-sum-iv/discuss/2385119/Python-DP
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target + 1) dp[0] = 1 for t in range(min(nums), target + 1): for n in nums: if n <= t: dp[t] += dp[t-n] return dp[-1]
combination-sum-iv
Python, DP
blue_sky5
0
18
combination sum iv
377
0.521
Medium
6,447
https://leetcode.com/problems/combination-sum-iv/discuss/2384416/Easy-python-solution-or-Combination-Sum-IV
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = { 0 : 1} for total in range(1,target + 1): dp[total] = 0 for n in nums: dp[total] += dp.get(total - n, 0) return dp[target]
combination-sum-iv
Easy python solution | Combination Sum IV
nishanrahman1994
0
16
combination sum iv
377
0.521
Medium
6,448
https://leetcode.com/problems/combination-sum-iv/discuss/2384320/Python-Dynamic-Programming-oror-Easy-to-understand
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = {0 : 1} for i in range(1, target+1): dp[i] = 0 for j in nums: dp[i] += dp.get(i - j, 0) return dp[target]
combination-sum-iv
Python - Dynamic Programming || Easy to understand
dayaniravi123
0
6
combination sum iv
377
0.521
Medium
6,449
https://leetcode.com/problems/combination-sum-iv/discuss/2384142/Python-Simple-Faster-Solution-using-DP-oror-Documented
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0]*(target+1) # dp array target+1 values dp[0] = 1 # bottom value is 1 # start from 1 to target for targetSum in range(1, target+1): # try with all numbers one by one for num in nums: if targetSum-num >= 0: # if positive dp[targetSum] += dp[targetSum-num] # count for given subproblem # return the final solution return dp[target]
combination-sum-iv
[Python] Simple Faster Solution using DP || Documented
Buntynara
0
8
combination sum iv
377
0.521
Medium
6,450
https://leetcode.com/problems/combination-sum-iv/discuss/2382305/Recursive-solution-faster-than-80
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: total = 0 @cache def getCombinations(n): t = 0 for i in nums: s = n + i if s == target: t += 1 elif s < target: t += getCombinations(s) return t for i in nums: if i == target: total += 1 total += getCombinations(i) return total
combination-sum-iv
Recursive solution, faster than 80%
pradyumna04
0
19
combination sum iv
377
0.521
Medium
6,451
https://leetcode.com/problems/combination-sum-iv/discuss/2382213/Python3-Solution-with-using-dp
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target + 1) dp[0] = 1 for i in range(1, target + 1): for num in nums: if num <= i: dp[i] += dp[i - num] return dp[-1]
combination-sum-iv
[Python3] Solution with using dp
maosipov11
0
5
combination sum iv
377
0.521
Medium
6,452
https://leetcode.com/problems/combination-sum-iv/discuss/2381754/GolangPython-DP-solution
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0 for _ in range(target+1)] dp[0] = 1 for i in range(len(dp)): for item in nums: if i-item >= 0: dp[i] += dp[i-item] return dp[-1]
combination-sum-iv
Golang/Python DP solution
vtalantsev
0
16
combination sum iv
377
0.521
Medium
6,453
https://leetcode.com/problems/combination-sum-iv/discuss/2381279/Basic-Memorization-Solution-or-Python
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [-1 for _ in range((target+1))] def helper(cur): if cur == target: return 1 if dp[cur] != -1: return dp[cur] dp[cur] = 0 for num in nums: if num + cur <= target: dp[cur] += helper(cur + num) return dp[cur] return helper(0)
combination-sum-iv
Basic Memorization Solution | Python
DigantaC
0
19
combination sum iv
377
0.521
Medium
6,454
https://leetcode.com/problems/combination-sum-iv/discuss/2381039/Python-or-Dynamic-Programming-or-Easy-or-Watch-once-or
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: #python dp function def dp(s,memo): if s==0: #if s become zero then increment count by one return 1 elif s<0: #if not than return zero #this step is imp return 0 elif s in memo: return memo[s] else: count = 0 for i in nums: #sp step reduce target/s to zero count+=dp(s-i,memo) memo[s] = count return count memo = {} return dp(target,memo)
combination-sum-iv
Python | Dynamic Programming | Easy | Watch once |
Brillianttyagi
0
36
combination sum iv
377
0.521
Medium
6,455
https://leetcode.com/problems/combination-sum-iv/discuss/2380972/python-dp
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [1] nums.sort() for i in range(target): t = i+1 temp = 0 for n in nums: if n<=t: temp += dp[t-n] else: break dp.append(temp) return dp[-1]
combination-sum-iv
python dp
li87o
0
29
combination sum iv
377
0.521
Medium
6,456
https://leetcode.com/problems/combination-sum-iv/discuss/2380832/Python-recursive-solution-with-memoization
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @lru_cache(None) def calculate(target): if target == 0: return 1 if target < 0: return 0 return sum(calculate(target - n) for n in nums) return calculate(target)
combination-sum-iv
Python recursive solution with memoization
996-YYDS
0
28
combination sum iv
377
0.521
Medium
6,457
https://leetcode.com/problems/combination-sum-iv/discuss/2380730/Python-5-lines
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @lru_cache(None) def backtrack(remain): if remain == 0: return 1 return sum(backtrack(remain - n) for n in nums if remain - n >= 0) return backtrack(target)
combination-sum-iv
Python 5 lines
SmittyWerbenjagermanjensen
0
55
combination sum iv
377
0.521
Medium
6,458
https://leetcode.com/problems/combination-sum-iv/discuss/2343065/Python-3-solution-99.4-time.-Tabulation-with-optimization
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: perms = [0] * (target + 1) perms[0] = 1 nums = set(nums) # putting nums in a set so they can be removed in O(1) time for i in range(len(perms)): if perms[i]: to_remove = set() # this is used to remove all nums that are too big from this iteration on for num in nums: try: # the slower alternative here is: if i + num <= target perms[i + num] += perms[i] except: # in the slower alternative this would be an else to_remove.add(num) nums.difference_update(to_remove) return perms[-1]
combination-sum-iv
Python 3 solution, 99.4% time. Tabulation with optimization
billbobsled
0
23
combination sum iv
377
0.521
Medium
6,459
https://leetcode.com/problems/combination-sum-iv/discuss/2080513/Python-or-Bottom-Up-DP-Simple-Approach
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: ''' Here we are doing bottom up DP and the base case would be => when target is zero how many way can we achieve that: 1 way ''' dp = { 0 : 1 } # base case for total in range(1,target+1): dp[total] = 0 for n in nums: dp[total] += dp.get(total-n,0) return dp[target]
combination-sum-iv
Python | Bottom-Up DP Simple Approach
__Asrar
0
56
combination sum iv
377
0.521
Medium
6,460
https://leetcode.com/problems/combination-sum-iv/discuss/1850437/Python-Backtracking-DP-solution-explained
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = {} return self.dfs(nums, target, dp) # backtracking with dp def dfs(self, nums, target, dp): # BASE CASES # your path lead you to # the target being zero or # the required path if target == 0: return 1 # at any point if your target becomes <0 # it means the current path is not feasible # backtrack, return 0 elif target < 0: return 0 elif target in dp: return dp[target] # for every num, recursively # calculate the num(ways) to reach # target out = 0 for i in range(len(nums)): # when you consider the current num[i] # the target also reduces by num[i] # so pass the updated target for recursion # # store all the ways possible for given # target in out to cache it later on out += self.dfs(nums, target-nums[i], dp) dp[target] = out return out
combination-sum-iv
[Python] Backtracking DP solution explained
buccatini
0
195
combination sum iv
377
0.521
Medium
6,461
https://leetcode.com/problems/combination-sum-iv/discuss/1554964/Python3-Solution
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target+1) dp[0] = 1 for i in range(1,target+1): for j in nums: if i-j >= 0: dp[i] += dp[i-j] return dp[target]
combination-sum-iv
Python3 Solution
satyam2001
0
125
combination sum iv
377
0.521
Medium
6,462
https://leetcode.com/problems/combination-sum-iv/discuss/1501249/Python-DP-Tabulation-Easy-to-understand
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [ 0 for _ in range(target+1) ] dp[0] = 1 for i in range(target): for num in nums: if i + num < target + 1: dp[i+num] += dp[i] return dp[-1] ```
combination-sum-iv
Python DP Tabulation Easy to understand
vharigovind9
0
110
combination sum iv
377
0.521
Medium
6,463
https://leetcode.com/problems/combination-sum-iv/discuss/1261949/Why-is-this-program-not-working-can-anyone-explain
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @functools.lru_cache(maxsize = None) ans = 0 def backtrack(target): nonlocal ans if target == 0: ans += 1 return for idx in range(len(nums)): val = nums[idx] if target - val >= 0: # target = possible_target backtrack(target - val) pass backtrack(target) return ans
combination-sum-iv
Why is this program not working can anyone explain
newborncoder
0
62
combination sum iv
377
0.521
Medium
6,464
https://leetcode.com/problems/combination-sum-iv/discuss/1166519/Python-oror-Simple-Explanation-oror-93-Faster-oror-DP
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp=[0]*(target+1) dp[0]=1 for i in range(1,target+1): for num in nums: if num<=i: dp[i]+=dp[i-num] return dp[-1]
combination-sum-iv
Python || Simple Explanation || 93% Faster || DP
abhi9Rai
0
127
combination sum iv
377
0.521
Medium
6,465
https://leetcode.com/problems/combination-sum-iv/discuss/1020406/Solution%3A-Combinations-Sum-4
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: nums.sort() dp = [0 for i in range(target+1)] dp[0] = 1 for comb_sum in range(target+1): for num in nums: if comb_sum - num >= 0: dp[comb_sum] = dp[comb_sum] + dp[comb_sum-num] return dp[target]
combination-sum-iv
Solution: Combinations Sum 4
UttasargaSingh
0
214
combination sum iv
377
0.521
Medium
6,466
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2233868/Simple-yet-best-Interview-Code-or-Python-Code-beats-90
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: m = len(matrix) n = len(matrix[0]) def count(m): c = 0 # count of element less than equals to 'm' i = n-1 j = 0 while i >= 0 and j < n: if matrix[i][j] > m: i -= 1 else: c += i+1 j += 1 return c low = matrix[0][0] high = matrix[n-1][n-1] while low <= high: m = (low+high)//2 cnt = count(m) if cnt < k: low = m + 1 else: cnt1 = count(m-1) if cnt1 < k: return m high = m-1 return 0
kth-smallest-element-in-a-sorted-matrix
✅ Simple yet best Interview Code | Python Code beats 90%
reinkarnation
5
532
kth smallest element in a sorted matrix
378
0.616
Medium
6,467
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1324393/Python-Merging-Arrays-Sorted-Manner
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: def merge_two(a, b): (m, n) = (len(a), len(b)) i = j = 0 d = [] while i < m and j < n: if a[i] <= b[j]: d.append(a[i]) i += 1 else: d.append(b[j]) j += 1 while i < m: d.append(a[i]) i += 1 while j < n: d.append(b[j]) j += 1 return d n=len(matrix) if n==1: return matrix[0][k-1] ans = list(merge(matrix[0],matrix[1])) for i in range(2,n): ans=list(merge(ans,matrix[i])) return ans[k-1]
kth-smallest-element-in-a-sorted-matrix
Python Merging Arrays Sorted Manner
sethhritik
4
335
kth smallest element in a sorted matrix
378
0.616
Medium
6,468
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368698/faster-than-98.81-using-python3(5-lines)
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: temp_arr=[] for i in matrix: temp_arr.extend(i) temp_arr.sort() return temp_arr[k-1]
kth-smallest-element-in-a-sorted-matrix
faster than 98.81% using python3(5 lines)
V_Bhavani_Prasad
3
102
kth smallest element in a sorted matrix
378
0.616
Medium
6,469
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368333/Python-or-Priority-queue
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: r = [] for i in range(len(matrix)): for j in range(len(matrix[i])): heappush(r, -matrix[i][j]) while len(r) > k: print(heappop(r)) return -heappop(r)
kth-smallest-element-in-a-sorted-matrix
Python | Priority queue
pivovar3al
1
65
kth smallest element in a sorted matrix
378
0.616
Medium
6,470
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367438/python3-or-easy-or-4-lines-of-code
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: arr = [] for i in range(min(len(matrix),k)): arr.extend(matrix[i]) arr.sort() return arr[k-1]
kth-smallest-element-in-a-sorted-matrix
python3 | easy | 4 lines of code
H-R-S
1
93
kth smallest element in a sorted matrix
378
0.616
Medium
6,471
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2293877/180ms-Faster-than-97-Solutions-oror-EASY-Python-Solution
'''class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: lst=[] for l in matrix: for i in l: lst.append(i) lst.sort() return lst[k-1]'''
kth-smallest-element-in-a-sorted-matrix
180ms Faster than 97% Solutions || EASY Python Solution
keertika27
1
115
kth smallest element in a sorted matrix
378
0.616
Medium
6,472
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1886129/Python3oror-Binary-Search-oror-Similar-to-Matrix-median
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: rows, cols = len(matrix), len(matrix[0]) total = rows * cols low, high = float('inf'), float('-inf') for r in range(rows): low = min(matrix[r][0],low) for c in range(cols): high = max(matrix[c][-1],high) while low <= high: mid = (low+high) // 2 cnt = 0 for r in range(rows): cnt += self.lesserEqual(matrix[r],mid) if cnt <= k-1: low = mid + 1 else: high = mid - 1 return low def lesserEqual(self,arr,target): low, high = 0, len(arr) - 1 while low <= high: mid = (low+high) // 2 if arr[mid] <= target: low = mid + 1 else: high = mid - 1 return low
kth-smallest-element-in-a-sorted-matrix
Python3|| Binary Search || Similar to Matrix median
s_m_d_29
1
278
kth smallest element in a sorted matrix
378
0.616
Medium
6,473
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1321854/Easy-and-simple-solution-in-python
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: flatten_list = sum(matrix, []) flatten_list.sort() return flatten_list[k-1]
kth-smallest-element-in-a-sorted-matrix
Easy & simple solution in python
maitysourab
1
270
kth smallest element in a sorted matrix
378
0.616
Medium
6,474
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/811809/Python3-summarizing-a-few-approaches
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(x for row in matrix for x in row)[k-1]
kth-smallest-element-in-a-sorted-matrix
[Python3] summarizing a few approaches
ye15
1
161
kth smallest element in a sorted matrix
378
0.616
Medium
6,475
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/811809/Python3-summarizing-a-few-approaches
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: n = len(matrix) hp = [(matrix[i][0], i, 0) for i in range(n)] # heap heapify(hp) for _ in range(k): v, i, j = heappop(hp) if j+1 < n: heappush(hp, (matrix[i][j+1], i, j+1)) return v
kth-smallest-element-in-a-sorted-matrix
[Python3] summarizing a few approaches
ye15
1
161
kth smallest element in a sorted matrix
378
0.616
Medium
6,476
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/811809/Python3-summarizing-a-few-approaches
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: n = len(matrix) def fn(x): """Return number of elements <= x""" ans = 0 i, j = 0, n-1 while i < n and 0 <= j: if matrix[i][j] <= x: ans += j+1 i += 1 else: j -= 1 return ans # "first true" binary serach # seach for first number whose f(x) >= k lo, hi = matrix[0][0], matrix[-1][-1] while lo < hi: mid = lo + hi >> 1 if fn(mid) < k: lo = mid + 1 else: hi = mid return lo
kth-smallest-element-in-a-sorted-matrix
[Python3] summarizing a few approaches
ye15
1
161
kth smallest element in a sorted matrix
378
0.616
Medium
6,477
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/670054/Python-easy-and-one-liner-solution
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(list(itertools.chain.from_iterable(matrix)))[k-1]
kth-smallest-element-in-a-sorted-matrix
Python easy and one liner solution
rajesh_26
1
276
kth smallest element in a sorted matrix
378
0.616
Medium
6,478
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2814591/Python3-Min-Heap
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: ROWS, COLS = len(matrix), len(matrix[0]) h = [(matrix[0][0], (0, 0))] visit = set({(0, 0)}) while k > 0: num, (r, c) = heapq.heappop(h) for dr, dc in [[0, 1], [1, 0]]: i, j = r+dr, c+dc if i < ROWS and j < COLS and (i, j) not in visit: visit.add((i, j)) heapq.heappush(h, (matrix[i][j], (i, j))) k -= 1 return matrix[r][c]
kth-smallest-element-in-a-sorted-matrix
[Python3] Min Heap
jonathanbrophy47
0
3
kth smallest element in a sorted matrix
378
0.616
Medium
6,479
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2806317/Python-or-O(n*n)-or-easy-peasy
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: l = [] n = len(matrix) for i in range(n): for j in matrix[i]: l.append(j) l.sort() return l[k-1]
kth-smallest-element-in-a-sorted-matrix
Python | O(n*n) | easy peasy
bhuvneshwar906
0
5
kth smallest element in a sorted matrix
378
0.616
Medium
6,480
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2790843/Beats-77-or-Came-up-with-this-during-Amazon-Interview
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: count = 0 m, n = len(matrix), len(matrix[0]) heap = [(matrix[0][0], (0,0))] dirs = [(1,0), (0,1), (1,1)] visited = set() while heap: cur, (i,j) = heapq.heappop(heap) count += 1 if count == k: return cur for dir_ in dirs: ix, jx = dir_ i_new, j_new = i+ix, j+jx if i_new < m and j_new < n: if (i_new, j_new) not in visited: visited.add((i_new, j_new)) heapq.heappush(heap, (matrix[i_new][j_new], (i_new, j_new)))
kth-smallest-element-in-a-sorted-matrix
Beats 77% | Came up with this during Amazon Interview
mihir_verma
0
4
kth smallest element in a sorted matrix
378
0.616
Medium
6,481
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2666677/Simple-Python-9080-O(n)-%2B-O(k-log-n)
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: if k == 1: return matrix[0][0] n = len(matrix) minheap = [None] * n for row in range(n): minheap[row] = ((matrix[row][0], row, 0)) # tuple of (value, row, col) # heapify(minheap) | optional if cols weren't sorted for i in range(k-1): val, row, col = heappop(minheap) if col+1 < n: heapq.heappush(minheap, (matrix[row][col+1], row, col+1)) return minheap[0][0]
kth-smallest-element-in-a-sorted-matrix
Simple Python [90%/80%] - O(n) + O(k log n)
LongQ
0
11
kth smallest element in a sorted matrix
378
0.616
Medium
6,482
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2513120/PYHTHON3-Solution-using-Heapify-oror-Faster-than-90.11-of-Python3-online-submissions
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: rank = [] for element in matrix: rank.extend(element) heapq.heapify(rank) while k > 0: final = heapq.heappop(rank) k -= 1 return final
kth-smallest-element-in-a-sorted-matrix
[PYHTHON3] Solution using Heapify || Faster than 90.11% of Python3 online submissions
WhiteBeardPirate
0
60
kth smallest element in a sorted matrix
378
0.616
Medium
6,483
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2407853/Python-Clean-Brute-Force
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted([num for lst in matrix for num in lst])[k-1]
kth-smallest-element-in-a-sorted-matrix
Python Clean Brute Force
tq326
0
44
kth smallest element in a sorted matrix
378
0.616
Medium
6,484
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2394035/Kth-Smallest-Element-in-a-Sorted-Matrix-Python-1-Line-Solution
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(list(sum(matrix, [])))[k-1]
kth-smallest-element-in-a-sorted-matrix
Kth Smallest Element in a Sorted Matrix Python 1 Line Solution
klu_2100031497
0
81
kth smallest element in a sorted matrix
378
0.616
Medium
6,485
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2393717/Python-O(N-*-log(max-min))-solution-no-extra-log-N-factor
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: lo, hi = matrix[0][0], matrix[-1][-1] # min, max def findIndex(matrix, val): ''' Returns Position where val can be inserted in O(m + n). All nums to right of result position will be >= val ''' addAt = 0 m, n = 1, len(matrix[0]) while m < len(matrix) + 1 and n > 0: if matrix[m - 1][n - 1] >= val: n -= 1 else: addAt += n m += 1 addAt += 1 return addAt while lo < hi: mid = (lo + hi)//2 if findIndex(matrix, mid) > k: hi = mid else: lo = mid + 1 if findIndex(matrix, lo) <= k: return lo return lo - 1
kth-smallest-element-in-a-sorted-matrix
Python O(N * log(max-min)) solution no extra log N factor
shubhparekh
0
131
kth smallest element in a sorted matrix
378
0.616
Medium
6,486
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2385185/Super-easy-python-oneliner
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(list(sum(matrix, [])))[k-1]
kth-smallest-element-in-a-sorted-matrix
Super easy python oneliner
pro6igy
0
30
kth smallest element in a sorted matrix
378
0.616
Medium
6,487
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2371664/Python-heap.-Two-variants.
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: n = len(matrix) heap = [(matrix[0][0], 0, 0)] matrix[0][0] = None while k > 1: _, r, c = heapq.heappop(heap) if r < n - 1 and matrix[r+1][c] is not None: heapq.heappush(heap, (matrix[r+1][c], r+1, c)) matrix[r+1][c] = None if c < n - 1 and matrix[r][c+1] is not None: heapq.heappush(heap, (matrix[r][c+1], r, c+1)) matrix[r][c+1] = None k -=1 return heap[0][0]
kth-smallest-element-in-a-sorted-matrix
Python, heap. Two variants.
blue_sky5
0
14
kth smallest element in a sorted matrix
378
0.616
Medium
6,488
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2371664/Python-heap.-Two-variants.
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: n = len(matrix) h = [(matrix[r][0], r, 0) for r in range(min(n, k))] heapq.heapify(h) while k > 1: _, r, c = heapq.heappop(h) if c < n - 1: heapq.heappush(h, (matrix[r][c+1], r, c + 1)) k -= 1 return h[0][0]
kth-smallest-element-in-a-sorted-matrix
Python, heap. Two variants.
blue_sky5
0
14
kth smallest element in a sorted matrix
378
0.616
Medium
6,489
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2371571/Only-1-Line-for-Code-KP's-solution
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(sum([i for i in matrix], []))[k - 1]
kth-smallest-element-in-a-sorted-matrix
Only 1 Line for Code, KP's solution
krishpatel13
0
12
kth smallest element in a sorted matrix
378
0.616
Medium
6,490
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2371038/Python-Easy-Solution-Top-90
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: ans = [] for i in matrix: ans.extend(i) return sorted(ans)[k-1]
kth-smallest-element-in-a-sorted-matrix
Python Easy Solution Top 90%
drblessing
0
27
kth smallest element in a sorted matrix
378
0.616
Medium
6,491
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2371038/Python-Easy-Solution-Top-90
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: ans = [] # Trim useless numbers N = len(matrix) if N > k: matrix = matrix[:k] for i in matrix: ans.extend(i) return sorted(ans)[k-1]
kth-smallest-element-in-a-sorted-matrix
Python Easy Solution Top 90%
drblessing
0
27
kth smallest element in a sorted matrix
378
0.616
Medium
6,492
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2370475/Python3-Solution-with-using-heap
class Solution: def kthSmallest(self, matrix, k): m, n = len(matrix), len(matrix[0]) heap = [] for i in range(len(matrix)): for j in range(len(matrix[i])): heappush(heap, -matrix[i][j]) if len(heap) > k: heappop(heap) return -heappop(heap)
kth-smallest-element-in-a-sorted-matrix
[Python3] Solution with using heap
maosipov11
0
13
kth smallest element in a sorted matrix
378
0.616
Medium
6,493
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2370475/Python3-Solution-with-using-heap
class Solution: def kthSmallest(self, matrix, k): heap = [] for r in range(len(matrix)): heapq.heappush(heap, (matrix[r][0], 0, r)) while k: elem, c, r = heapq.heappop(heap) if c < len(matrix[r]) - 1: heapq.heappush(heap, (matrix[r][c + 1], c + 1, r)) k -= 1 return elem
kth-smallest-element-in-a-sorted-matrix
[Python3] Solution with using heap
maosipov11
0
13
kth smallest element in a sorted matrix
378
0.616
Medium
6,494
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368821/One-line-code-in-Python-very-easy-to-understand
class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ return sorted(sum(matrix, []))[k-1]
kth-smallest-element-in-a-sorted-matrix
One line code in Python very easy to understand
hsaikrishna1999
0
18
kth smallest element in a sorted matrix
378
0.616
Medium
6,495
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368782/Python-Binary-Search-Solution-bisect_right-(upper_bound)-oror-Documented
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: # count elements that are less than val def count_elements_less_than(val): count = 0 for row in matrix: # upper bound of val in the row count += bisect_right(row, val) return count # binary search pointers: low and high low, high = matrix[0][0], matrix[-1][-1] # Repeat until the pointers satisfy: low < high while low < high: mid = (low + high) // 2 # middle point - pivot if count_elements_less_than(mid) < k: low = mid + 1; # shrink from left side else: high = mid # shrink from right side return low
kth-smallest-element-in-a-sorted-matrix
[Python] Binary Search Solution - bisect_right (upper_bound) || Documented
Buntynara
0
9
kth smallest element in a sorted matrix
378
0.616
Medium
6,496
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368517/Python-oror-SImple-Soultion-oror-easy-understanding
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: temp_matrix = [] for i in matrix: temp_matrix.extend(i) return sorted(temp_matrix)[k-1]
kth-smallest-element-in-a-sorted-matrix
Python || SImple Soultion || easy understanding
noobj097
0
7
kth smallest element in a sorted matrix
378
0.616
Medium
6,497
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368498/Lazy-Solution-Lazy-Language..-You-know-what-%3A)
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted([x for r in matrix for x in r])[k-1]
kth-smallest-element-in-a-sorted-matrix
Lazy Solution, Lazy Language.. You know what?? :)
yours-truly-rshi
0
16
kth smallest element in a sorted matrix
378
0.616
Medium
6,498
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2368417/Simpler-and-Faster-execution-in-python3
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: blank = [] for i in matrix: blank.extend(i) blank.sort() if(len(blank)!=0): return blank[k-1] return
kth-smallest-element-in-a-sorted-matrix
Simpler and Faster execution in python3
ujs_lc_99
0
9
kth smallest element in a sorted matrix
378
0.616
Medium
6,499