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/max-area-of-island/discuss/2305261/Python-Optimized-DFS-Solution
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: rows = len(grid) cols = len(grid[0]) def dfs(i, j): if grid[i][j] == 1: grid[i][j] = 0 return 1 + goToLeft(i, j-1) + goToRight(i, j+1) + goToTop(i-1, j) + goToBottom(i+1, j) else: return 0 def goToLeft(i, j): return 0 if j < 0 else dfs(i, j) def goToRight(i, j): return 0 if j >= cols else dfs(i, j) def goToTop(i, j): return 0 if i < 0 else dfs(i, j) def goToBottom(i, j): return 0 if i >= rows else dfs(i, j) area = 0 for i in range(rows): for j in range(cols): area = max(dfs(i, j), area) return area
max-area-of-island
[Python] Optimized DFS Solution
Buntynara
0
39
max area of island
695
0.717
Medium
11,500
https://leetcode.com/problems/max-area-of-island/discuss/2296706/python3-bfs
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: row = len(grid) col = len(grid[0]) total = 0 for r in range(row): for c in range(col): if grid[r][c] == 1: q = collections.deque() land = 0 #used to record the area of each possible island q.append([r,c]) land += 1 grid[r][c] = 0 while q: #bfs x,y = q.popleft() for nx, ny in [[x+1,y], [x,y+1], [x-1,y], [x,y-1]]: if 0 <= nx < row and 0 <= ny < col and grid[nx][ny] == 1: q.append([nx,ny]) land += 1 grid[nx][ny] = 0 total = max(total, land) #update the final result after each island is 100% traversed return total
max-area-of-island
python3 bfs
yhh1
0
25
max area of island
695
0.717
Medium
11,501
https://leetcode.com/problems/max-area-of-island/discuss/2287925/Basic-Python-BFS-solution-beats-90
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: if not grid: return 0 len_row = len(grid) len_col = len(grid[0]) directions = [(0,1),(1,0),(-1,0),(0,-1)] def bfs(start_row,start_col): area = 1 queue = [(start_row, start_col)] while queue: row, col = queue.pop() for r,c in directions: new_r = r + row new_c = c + col while 0 <= new_r < len_row and 0<= new_c < len_col and grid[new_r][new_c] == 1: queue.append((new_r,new_c)) grid[new_r][new_c] = 2 #instead of using an extra visited set area += 1 return area -1 if area > 1 else 1 result = 0 for r in range(len_row): for c in range(len_col): if grid[r][c] ==1: area = bfs(r,c) grid[r][c] = 2 result = max(result,area) return result
max-area-of-island
Basic Python BFS solution, beats 90%
prejudice23
0
20
max area of island
695
0.717
Medium
11,502
https://leetcode.com/problems/max-area-of-island/discuss/2287137/Python3-dfs-solution
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: res=0 n=len(grid) m=len(grid[0]) def isValid(x,y): return n>x>=0 and m>y>=0 self.visited=[[0 for j in range(m)] for i in range(n)] dirs=[[-1,0],[1,0],[0,-1],[0,1]] def dfs(i,j): if self.visited[i][j]: return 0 t=1 self.visited[i][j]=1 for dx,dy in dirs: x=dx+i y=dy+j if isValid(x,y) and grid[x][y]==1 and self.visited[x][y]==0: t+=dfs(x,y) return t for i in range(n): for j in range(m): if grid[i][j]==1 and self.visited[i][j]==0: res=max(res,dfs(i,j)) return res
max-area-of-island
Python3 dfs solution
atm1504
0
8
max area of island
695
0.717
Medium
11,503
https://leetcode.com/problems/max-area-of-island/discuss/2287118/Simple-intuitive-dfs-change-the-grid-value-move-updownrightleft-%3A)
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: def dfs(i,j): if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j]==0: return 0 grid[i][j]=0 down = dfs(i+1,j) up = dfs(i-1,j) right = dfs(i,j+1) left = dfs(i,j-1) a = 1+(up+down+right+left) return a ans = 0 for row in range(len(grid)): for col in range(len(grid[0])): ans = max(ans,dfs(row,col)) return ans
max-area-of-island
Simple intuitive dfs - change the grid value - move up,down,right,left :)
ana_2kacer
0
9
max area of island
695
0.717
Medium
11,504
https://leetcode.com/problems/count-binary-substrings/discuss/384054/Only-using-stack-with-one-iteration-logic-solution-in-Python-O(N)
class Solution: def countBinarySubstrings(self, s: str) -> int: stack = [[], []] latest = int(s[0]) stack[latest].append(latest) result = 0 for i in range(1,len(s)): v = int(s[i]) if v != latest: stack[v].clear() latest = v stack[v].append(v) if len(stack[1-v]) > 0: stack[1-v].pop() result += 1 return result
count-binary-substrings
Only using stack with one iteration, logic solution in Python O(N)
zouqiwu09
7
994
count binary substrings
696
0.656
Easy
11,505
https://leetcode.com/problems/count-binary-substrings/discuss/1849843/python-3-oror-O(n)-oror-O(1)
class Solution: def countBinarySubstrings(self, s: str) -> int: prev, cur = 0, 1 res = 0 for i in range(1, len(s)): if s[i] == s[i - 1]: cur += 1 else: prev, cur = cur, 1 if cur <= prev: res += 1 return res
count-binary-substrings
python 3 || O(n) || O(1)
dereky4
2
462
count binary substrings
696
0.656
Easy
11,506
https://leetcode.com/problems/count-binary-substrings/discuss/2273332/Python-3-O(n)-solution-faster-then-maximum-submission
class Solution: def countBinarySubstrings(self, s: str) -> int: prev , curr , res = 0 , 1 , 0 for i in range(1,len(s)): if s[i-1] == s[i]: curr +=1 else: prev = curr curr = 1 if prev >= curr: res+=1 return res
count-binary-substrings
Python 3 O(n) solution faster then maximum submission
ronipaul9972
1
283
count binary substrings
696
0.656
Easy
11,507
https://leetcode.com/problems/count-binary-substrings/discuss/380683/Solution-in-Python-3-(one-line)
class Solution: def countBinarySubstrings(self, s: str) -> int: L = len(s) a = [-1]+[i for i in range(L-1) if s[i] != s[i+1]]+[L-1] b = [a[i]-a[i-1] for i in range(1,len(a))] c = [min(b[i-1],b[i]) for i in range(1,len(b))] return sum(c)
count-binary-substrings
Solution in Python 3 (one line)
junaidmansuri
1
731
count binary substrings
696
0.656
Easy
11,508
https://leetcode.com/problems/count-binary-substrings/discuss/380683/Solution-in-Python-3-(one-line)
class Solution: def countBinarySubstrings(self, s: str) -> int: return sum((lambda x: [min(x[i]-x[i-1],x[i+1]-x[i]) for i in range(1,len(x)-1)])([-1]+[i for i in range(len(s)-1) if s[i] != s[i+1]]+[len(s)-1])) - Junaid Mansuri (LeetCode ID)@hotmail.com
count-binary-substrings
Solution in Python 3 (one line)
junaidmansuri
1
731
count binary substrings
696
0.656
Easy
11,509
https://leetcode.com/problems/count-binary-substrings/discuss/2180709/python-straght-forward-2-pointers
class Solution: def countBinarySubstrings(self, s: str) -> int: n = len(s) left = right = 0 res = 0 for i in range(1, n): if s[i] != s[i-1]: left = i -1 right = i while left >= 0 and right < n and s[left] == s[i-1] and s[right] == s[i]: if s[left] != s[right]: left -= 1 right += 1 res += 1 else: break return res
count-binary-substrings
python straght forward, 2 pointers
hardernharder
0
237
count binary substrings
696
0.656
Easy
11,510
https://leetcode.com/problems/count-binary-substrings/discuss/2087348/Python3-Simple-approach-beats-96-in-time-and-98-in-space
class Solution: def countBinarySubstrings(self, s: str) -> int: ret_val = 0 ones = 0 zeros = 0 prev = s[0] for bit in s: if bit == "1": if prev == "0": ones = 0 ones += 1 if zeros > 0: ret_val += 1 zeros -= 1 else: if prev == "1": zeros=0 zeros += 1 if ones > 0: ret_val += 1 ones -= 1 #print("zeros :{} \nones :{} ".format(zeros, ones)) prev = bit return ret_val
count-binary-substrings
Python3 Simple approach, beats 96% in time and 98% in space
kukamble
0
222
count binary substrings
696
0.656
Easy
11,511
https://leetcode.com/problems/count-binary-substrings/discuss/1982595/Python-Solution
class Solution: def countBinarySubstrings(self, s: str) -> int: slen = len(s) index = 0 interval = [] while index < slen: cnt = 1 while index + 1 < slen and s[index + 1] == s[index]: cnt += 1 index += 1 interval.append(cnt) index += 1 ans = 0 for i in range(1, len(interval)): ans += min(interval[i], interval[i-1]) return ans
count-binary-substrings
Python Solution
DietCoke777
0
103
count binary substrings
696
0.656
Easy
11,512
https://leetcode.com/problems/count-binary-substrings/discuss/1735320/Python3-solution-using-list-comprehensions
class Solution: def countBinarySubstrings(self, s: str) -> int: # Find the index where each change occurs, pick this apart by trying out `list(zip(s, s[1:]))` and then the enumeration # Note we need to add index 0 and index len(s) for this to calculate correctly indexes = [0] + [i for i, (l, r) in enumerate(zip(s, s[1:]), start=1) if l != r] + [len(s)] # Find the length of the group by grouping the above indexes and finding the difference groups = [b - a for a, b in zip(indexes, indexes[1:])] # Get the grouping (again in pairs) of the above group lengths, find the min, and then take the sum of all the mins return sum(min(x, y) for x, y in zip(groups, groups[1:]))
count-binary-substrings
Python3 solution using list comprehensions
mike72
0
164
count binary substrings
696
0.656
Easy
11,513
https://leetcode.com/problems/count-binary-substrings/discuss/1551757/O(n)-Time-Python-3-Solution
class Solution: def countBinarySubstrings(self, s: str) -> int: curr = s[0] change_index_list = [] change_index_list.append(0) for i in range(1, len(s)): if curr != s[i]: curr = s[i] change_index_list.append(i) change_index_list.append(len(s)) count = 0 for j in range(1,len(change_index_list)-1): count += min(change_index_list[j] - change_index_list[j-1], change_index_list[j+1] - change_index_list[j]) return count
count-binary-substrings
O(n) Time Python 3 Solution
zzjharry
0
442
count binary substrings
696
0.656
Easy
11,514
https://leetcode.com/problems/count-binary-substrings/discuss/1173477/Python-solution.-Expand-from-middle-of-'01'-or-'10'
class Solution: def countBinarySubstrings(self, s: str) -> int: def helper(left, right): count = 1 while left - 1 >= 0 and right + 1 < len(s) and s[left] == s[left-1] and s[right] == s[right+1]: count += 1 left -= 1 right += 1 return count result = 0 for i in range(len(s) - 1): if s[i] != s[i+1]: result += helper(i, i+1) return result
count-binary-substrings
Python solution. Expand from middle of '01' or '10'
pochy
0
74
count binary substrings
696
0.656
Easy
11,515
https://leetcode.com/problems/count-binary-substrings/discuss/1173109/Python3-linear-sweep
class Solution: def countBinarySubstrings(self, s: str) -> int: ans = prev = curr = 0 for i in range(len(s)+1): if i == len(s) or i and s[i-1] != s[i]: ans += min(prev, curr) prev = curr curr = 1 else: curr += 1 return ans
count-binary-substrings
[Python3] linear sweep
ye15
0
51
count binary substrings
696
0.656
Easy
11,516
https://leetcode.com/problems/count-binary-substrings/discuss/1173086/Simple-solution-using-a-binary-like-counter-for-both-types-of-characters-in-Python3
class Solution: def countBinarySubstrings(self, s: str) -> int: c = [0, 0] c[int(s[0])] += 1 ans = 0 for i in range(1, len(s)): if s[i] == s[i - 1]: c[int(s[i])] += 1 else: c[int(s[i])] = 1 if c[abs(int(s[i]) - 1)] > 0: c[abs(int(s[i]) - 1)] -= 1 ans += 1 return ans
count-binary-substrings
Simple solution using a binary like counter for both types of characters in Python3
amoghrajesh1999
0
124
count binary substrings
696
0.656
Easy
11,517
https://leetcode.com/problems/count-binary-substrings/discuss/1172942/Easy-Solution-Python-3
class Solution: def countBinarySubstrings(self, s: str) -> int: occ,acc,res=[],1,0 for i in range(1,len(s)): if s[i]==s[i-1]: acc+=1 else: occ.append(acc) acc=1 occ.append(acc) print(occ) for i in range(1,len(occ)): res+=min(occ[i],occ[i-1]) return res
count-binary-substrings
Easy Solution Python 3
moazmar
0
170
count binary substrings
696
0.656
Easy
11,518
https://leetcode.com/problems/count-binary-substrings/discuss/1507982/Groupby-contiguous-blocks-86-speed
class Solution: def countBinarySubstrings(self, s: str) -> int: group_lens = [len(list(g)) for _, g in groupby(s)] return sum(min(a, b) for a, b in zip(group_lens, group_lens[1:]))
count-binary-substrings
Groupby contiguous blocks, 86% speed
EvgenySH
-1
272
count binary substrings
696
0.656
Easy
11,519
https://leetcode.com/problems/degree-of-an-array/discuss/349801/Solution-in-Python-3-(beats-~98)
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: C = {} for i, n in enumerate(nums): if n in C: C[n].append(i) else: C[n] = [i] M = max([len(i) for i in C.values()]) return min([i[-1]-i[0] for i in C.values() if len(i) == M]) + 1 - Junaid Mansuri
degree-of-an-array
Solution in Python 3 (beats ~98%)
junaidmansuri
43
3,000
degree of an array
697
0.559
Easy
11,520
https://leetcode.com/problems/degree-of-an-array/discuss/1179769/Simple-Python-Solution-with-explanation-O(n)
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: ''' step 1: find the degree - create a hashmap of a number and value as list of occurance indices - the largest indices array in the hashmap gives us the degree step 2: find the minimum length subarray with same degree - initialize result as length of array - for each indices array, if it's length equals degree, means it's most frequent element - this length will be equal to the difference of first occurance and last occurance of most frequent element - compare this length with current result and keep the smallest length as result - return result + 1 because difference of indices will give us length - 1 ''' c = defaultdict(list) for i, n in enumerate(nums): c[n].append(i) degree = max([len(x) for x in c.values()]) result = len(nums) for indices in c.values(): if len(indices) == degree: result = min(result, indices[-1] - indices[0]) return result + 1
degree-of-an-array
Simple Python Solution with explanation - O(n)
jitin11
10
888
degree of an array
697
0.559
Easy
11,521
https://leetcode.com/problems/degree-of-an-array/discuss/434794/Python3-solution-or-Beat-100
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: if nums == []: return 0 dic = {} for n in nums: if n not in dic: dic[n] = 1 else: dic[n] += 1 degree = max(dic.values()) if degree == 1: return 1 else: min_length = len(nums) for keys in dic: if dic[keys] == degree: pos1 = nums.index(keys) pos2 = len(nums) -nums[::-1].index(keys) - 1 if pos2 - pos1 + 1 < min_length: min_length = pos2 - pos1 + 1 return min_length
degree-of-an-array
Python3 solution | Beat 100%
YuanYao666
2
382
degree of an array
697
0.559
Easy
11,522
https://leetcode.com/problems/degree-of-an-array/discuss/1697602/Python-or-just-23-line-code-or-Dictionary-or-O(N)-time
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: frq = defaultdict(int) # frequency map for nums fnl = {} # stores first and last index of each num deg = 0 # degree for i in range(len(nums)): frq[nums[i]] += 1 deg = max(deg, frq[nums[i]]) if nums[i] in fnl: fnl[nums[i]][1] = i else: fnl[nums[i]] = [i,i] res = len(nums) for num in frq: if frq[num] != deg: continue res = min(res, fnl[num][1] - fnl[num][0] + 1) return res
degree-of-an-array
[Python] | just 23 line code | Dictionary | O(N) time
Divyanshuk34
1
186
degree of an array
697
0.559
Easy
11,523
https://leetcode.com/problems/degree-of-an-array/discuss/1669876/Python3-Straight-forward-statistic
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: if not nums: return 0 stats = {} for i, n in enumerate(nums): if n not in stats: stats[n] = {"start":i, "end":i, "count":1} else: stats[n]["end"] = i stats[n]["count"] += 1 degree = 1 length = 1 for v in stats.values(): if v["count"] > degree: degree = v["count"] length = v["end"] - v["start"] + 1 elif v["count"] == degree: length = min(length, v["end"] - v["start"] + 1) return length
degree-of-an-array
[Python3] Straight forward statistic
BigTailWolf
1
82
degree of an array
697
0.559
Easy
11,524
https://leetcode.com/problems/degree-of-an-array/discuss/1375342/90.17-faster
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: maxv=0 d={} count=1000000 for i in nums: if i in d: d[i]+=1 maxv=max(maxv, d[i]) else: d[i]=1 if maxv<=1: return 1 for i, k in d.items(): start=end=0 if k==maxv: for num in range(len(nums)): if nums[num]==i: start=num break for num in range(len(nums)-1,-1,-1): if nums[num]==i: end=num break else: continue if count>(end-start+1): count=end-start+1 print(count) return count
degree-of-an-array
90.17% faster
prajwalahluwalia
1
218
degree of an array
697
0.559
Easy
11,525
https://leetcode.com/problems/degree-of-an-array/discuss/2732712/Simple-Python-Solution-%3A
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: d = {} min_len = len(nums)+1 max_deg = 0 for i in range(len(nums)): if nums[i] not in d.keys(): d[nums[i]] = [ 1,i,1] else: d[nums[i]][0] += 1 d[nums[i]][2] = i-d[nums[i]][1]+1 for i in d.values(): if i[0]>max_deg : max_deg = i[0] min_len = i[2] elif i[0]==max_deg : min_len = i[2] if i[2] < min_len else min_len return min_len
degree-of-an-array
Simple Python Solution :
MaviOp
0
5
degree of an array
697
0.559
Easy
11,526
https://leetcode.com/problems/degree-of-an-array/discuss/2319915/Fast-python-with-explanation
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: dict_ = {} l=len(nums) for i in range(l): if nums[i] in dict_: dict_[nums[i]][0]+=1 dict_[nums[i]][2]=i-dict_[nums[i]][1] #updating difference between first and last idx else: dict_[nums[i]] = [1,i,0] #count, first idx, difference between first and last idx max_c=0 for i in dict_: max_c = max(max_c,dict_[i][0]) #getting max occurence #print(max_c) nums_max_c = [] for i in dict_: if dict_[i][0] == max_c: nums_max_c.append(i) #getting numbers with max occurence #print(nums_max_c) min_dist=51000 for i in nums_max_c: min_dist = min(min_dist,dict_[i][2]) #getting min distance between first and last idx among selected numbers return min_dist+1
degree-of-an-array
Fast python with explanation
sunakshi132
0
71
degree of an array
697
0.559
Easy
11,527
https://leetcode.com/problems/degree-of-an-array/discuss/2282461/Python-3-dicts-with-defaultdict-for-cleaner-code
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: maxFreq = 0 count = defaultdict(lambda: 0) minPos = defaultdict(lambda: 100000) maxPos = defaultdict(lambda: -1) for i, n in enumerate(nums): count[n] += 1 minPos[n] = min(minPos[n], i) maxPos[n] = max(maxPos[n], i) if count[n] > maxFreq: maxFreq = count[n] dists = [maxPos[elem] - minPos[elem] + 1 for elem in count.keys() if count[elem] == maxFreq] return min(dists)
degree-of-an-array
Python, 3 dicts with defaultdict for cleaner code
boris17
0
40
degree of an array
697
0.559
Easy
11,528
https://leetcode.com/problems/degree-of-an-array/discuss/2158324/C%2B%2BPython-optimal-solution-with-comments
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: m = {} # dict to store freq, first index and last index maxf,ans = 0,inf for i, num in enumerate(nums): # if this is the first time we encounter this number # then simply initialize frequency as 1 and index of first and last occurence as current index if num not in m: m[num] = [1,i,i] # otherwise increase frequency by 1 and update index of last occurence else: m[num][0] += 1 m[num][2] = i maxf = max(maxf,m[num][0]) # finally iterate through the dict # since we don't need the actual number, we can only iterate through the values # for every value have max frequency, update the answer for tup in m.values(): if tup[0] == maxf: ans = min(ans,tup[2] - tup[1] + 1) return ans
degree-of-an-array
[C++/Python optimal solution with comments
chaitanya_29
0
52
degree of an array
697
0.559
Easy
11,529
https://leetcode.com/problems/degree-of-an-array/discuss/1312521/Python3-dollarolution-(84-faster-and-98-better-memory-usage)
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: d = {} m, j, count = 1, [nums[0]], [] for i in nums: if i not in d: d[i] = 1 else: d[i] += 1 if d[i] > m: m = d[i] j = [i] elif d[i] == m: j.append(i) for i in j: count.append(len(nums) - nums[::-1].index(i) - nums.index(i)) return min(count)
degree-of-an-array
Python3 $olution (84% faster & 98% better memory usage)
AakRay
0
439
degree of an array
697
0.559
Easy
11,530
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1627241/python-simple-with-detailed-explanation-or-96.13
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if k==1: return True total = sum(nums) n = len(nums) if total%k!=0: return False nums.sort(reverse=True) average = total//k if nums[0]>average: return False visited = [False]*n def dfs(cur, begin, k): if k==0: return True if cur>average: return False elif cur==average: return dfs(0, 0, k-1) for i in range(begin, n): if not visited[i]: visited[i] = True if dfs(cur + nums[i], i+1, k): return True visited[i] = False return False return dfs(0, 0, k)
partition-to-k-equal-sum-subsets
python simple with detailed explanation | 96.13%
1579901970cg
5
563
partition to k equal sum subsets
698
0.408
Medium
11,531
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1772609/Python3-Solution-with-DFS
class Solution(object): def canPartitionKSubsets(self, nums, k): target = sum(nums) if target % k != 0: return False target //= k cur = [0] * k; nums.sort( reverse = True) def foo( index): if index == len( nums): return True for i in range( k): if nums[index] + cur[i] <= target: cur[i] += nums[index] if foo( index + 1) == True: return True cur[i] -= nums[index] if cur[i] == 0: break return False return foo( 0)
partition-to-k-equal-sum-subsets
Python3 Solution with DFS
JuboGe
2
190
partition to k equal sum subsets
698
0.408
Medium
11,532
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2837264/Python-Backtrack-%2B-Exploiting-%40Cache
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if sum(nums) % k != 0: return False target = sum(nums) // k if any(num > target for num in nums): return False nums.sort() while target in nums: nums.remove(target) k -= 1 seen = [False] * len(nums) @cache def bp(seen, i, total, k): if k == 0: return True if k == 1 and total == 0: return True if i == len(nums) or total < 0: return False #Reset when we successfully find a partition sum == target if total == 0: total = target k -= 1 i = 0 seen = list(seen) if seen[i] == False: seen[i] = True if bp(tuple(seen), i + 1, total - nums[i], k): return True seen[i] = False return bp(tuple(seen), i + 1, total, k) return bp(tuple(seen), 0, target, k)
partition-to-k-equal-sum-subsets
[Python] Backtrack + Exploiting @Cache
Nezuko-NoBamboo
1
43
partition to k equal sum subsets
698
0.408
Medium
11,533
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2054135/Python-DFS-Solution
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: n, expected_sum = len(nums), sum(nums) / k nums.sort(reverse=True) if expected_sum != int(expected_sum) or nums[0] > expected_sum: return False def btrack(pos, target, done): if done == k-1: return True if pos == n: return False num = nums[pos] if num > target: return btrack(pos + 1, target, done) nums[pos] = expected_sum + 1 if num == target: return btrack(0, expected_sum, done + 1) if btrack(pos + 1, target - num, done): return True nums[pos] = num return btrack(pos + 1, target, done) return btrack(0, expected_sum, 0)
partition-to-k-equal-sum-subsets
Python DFS Solution
TongHeartYes
1
125
partition to k equal sum subsets
698
0.408
Medium
11,534
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1385240/Intuitive-recursive-solution-(less-15-lines)-WITHOUT-bitmask-or-visited-maps.
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) if total%k: return False partitions = [total//k]*k # Sorting was an after thought to get rid of the TLEs nums.sort(reverse=True) # Attempt allocating nums to the partitions, backtrack if not possible def f(i): if i >= len(nums): return True for idx in range(k): if nums[i] <= partitions[idx]: partitions[idx] -= nums[i] if f(i+1): return True partitions[idx] += nums[i] return f(0)
partition-to-k-equal-sum-subsets
Intuitive recursive solution (< 15 lines) WITHOUT bitmask or visited maps.
worker-bee
1
123
partition to k equal sum subsets
698
0.408
Medium
11,535
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2839608/Python-Backtrack
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if sum(nums) % k != 0: return False target = sum(nums) // k if any(num > target for num in nums): return False nums.sort() while target in nums: nums.remove(target) k -= 1 seen = [False] * len(nums) @cache def bp(seen, i, total, k): if k == 0: return True if k == 1 and total == 0: return True if i == len(nums) or total < 0: return False #Reset when we successfully find a partition sum == target if total == 0: total = target k -= 1 i = 0 seen = list(seen) if seen[i] == False: seen[i] = True if bp(tuple(seen), i + 1, total - nums[i], k): return True seen[i] = False return bp(tuple(seen), i + 1, total, k) return bp(tuple(seen), 0, target, k)
partition-to-k-equal-sum-subsets
Python Backtrack
Farawayy
0
1
partition to k equal sum subsets
698
0.408
Medium
11,536
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2837456/backtrack-python-no-time-limit-exceeded
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) if total%k != 0: return False target = total//k n = len(nums) buckets = [0 for _ in range(k)] nums.sort(reverse=True) def backtrack(buckets, index, t): if index == n: for i in buckets: if i != t: return False return True for idx in range(len(buckets)): if buckets[idx]+nums[index] > target: continue buckets[idx] += nums[index] if backtrack(buckets, index+1, t): return True buckets[idx] -= nums[index] if buckets[idx] == 0: break return False return backtrack(buckets, 0, target)
partition-to-k-equal-sum-subsets
backtrack python no time limit exceeded
ychhhen
0
2
partition to k equal sum subsets
698
0.408
Medium
11,537
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2837400/Python-Solution-using-Backtracking
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) if total % k: return False target = total // k subSets = [0] * k nums.sort(reverse = True) used = [False] * len(nums) def backtrack(i, k, tot): if k == 0: return True if tot == target: return backtrack(0, k - 1, 0) for j in range(i, len(nums)): # pruning1: After reversed sorting, the duplicate elements are next to each other, if we can skip the first one, we can skip all the following duplicate one. if j > 0 and not used[j - 1] and nums[j] == nums[j - 1]: continue if used[j] or tot + nums[j] > target: continue used[j] = True if backtrack(j + 1, k, tot + nums[j]): return True used[j] = False # Pruning2: # since we sort nums in reverse order, tot == 0 means skipping the first element, if it cannot work, the rest of the elements cannot work either, we can just break the loop and return False. # tot + nums[j] == target: if tot == 0 or tot + nums[j] == target: break # return False return False return backtrack(0, k, 0)
partition-to-k-equal-sum-subsets
Python Solution using Backtracking
taoxinyyyun
0
1
partition to k equal sum subsets
698
0.408
Medium
11,538
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2752864/Python-backtracking-solution
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) n = len(nums) if total%k != 0: return False nums.sort(reverse=True) target = total // k used = [False] * n memo = {} # Record the current state of used array when a bucket is full def backtracking(start_index, k_left, cur_sum): """ start_index: the start index of balls k_left: remaining buskets to fill cur_sum: the sum of balls in current bucket """ if k_left==0: return True if tuple(used) in memo: return memo[tuple(used)] if cur_sum==target: tmp = backtracking(0, k_left-1, 0) memo[tuple(used)] = tmp return tmp for i in range(start_index, n): if nums[i]>target or cur_sum+nums[i]>target or used[i]: continue used[i] = True cur_sum += nums[i] if backtracking(i+1, k_left, cur_sum): return True used[i] = False cur_sum -= nums[i] return False return backtracking(0, k, 0)
partition-to-k-equal-sum-subsets
Python backtracking solution
gcheng81
0
7
partition to k equal sum subsets
698
0.408
Medium
11,539
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2751927/python
# class Solution: # def backtrack(self, used, bucket, start, k): # if k == 0: # return True # if bucket == self.target: # return self.backtrack(used[:], 0, 0, k-1) # for i in range(start, self.n): # if used[i]: # continue # if self.nums[i] + bucket > self.target: # continue # used[i] = True # bucket += self.nums[i] # if self.backtrack(used[:], bucket, i+1, k): # return True # used[i] = False # bucket -= self.nums[i] # return False # def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: # if k > len(nums): # return False # sums = sum(nums) # if sums % k > 0: # return False # self.nums = nums # self.target = sums/k # self.n = len(nums) # used = [False for _ in range(self.n)] # return self.backtrack(used, 0, 0, k) class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: # exclude obvious cases if k > len(nums): return False s = sum(nums) if s % k: return False # target is the target sum of each bucket target = int(s / k) # k buckets record the sum of each bucket buckets = [0 for _ in range(k)] # used[i] to record nums[i] used or not used = [False for _ in range(len(nums))] # memo to record the state of used for pruning memo = {} # reverse nums nums = sorted(nums, reverse = True) def backtrack(k, bucket, start): # base case if k == 0: # all buckets are filled return True # stringfy used to record current state state = str(used) if bucket == target: # current bucket has been filled, go to next bucket temp = backtrack(k-1, 0, 0) # record this state to memo memo[state] = temp return temp # if this state exist in memo, return previous result if state in memo: return memo[state] # travere from start to get nums[i] to fill in bucket for i in range(start, len(nums)): # pruning if used[i]: continue # bucket already full if(nums[i] + bucket > target): continue # choice fill this bucket or not used[i] = True bucket += nums[i] # go to next if backtrack(k, bucket, i+1): return True used[i] = False bucket -= nums[i] return False res = backtrack(k, 0, 0) return res
partition-to-k-equal-sum-subsets
python
lucy_sea
0
8
partition to k equal sum subsets
698
0.408
Medium
11,540
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2750438/Python-Backtrack-Solution
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: target = sum(nums) / k n = len(nums) seen = [False for _ in range(n)] memo = {} nums.sort(reverse=True) if target != int(target): return False # k bigger than length of nums if k > n: return False def dfs(total, bucket, start): """ total: remaining busket to fill bucket: the number of current bucket start: the start index of balls to fill in the busket """ # All buskets have been filled if total == 0: return True if tuple(seen) in memo: return memo[tuple(seen)] if bucket == target: res = dfs(total-1, 0, 0) memo[tuple(seen)] = res return res b for i in range(start, n): if seen[i]: continue if nums[i] + bucket > target: continue seen[i] = True bucket += nums[i] if dfs(total, bucket, i+1): return True seen[i] = False bucket -= nums[i] return False return dfs(k, 0, 0)
partition-to-k-equal-sum-subsets
Python Backtrack Solution
Rui_Liu_Rachel
0
8
partition to k equal sum subsets
698
0.408
Medium
11,541
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2346059/Python3-Solution-or-Backtracking
class Solution: def canPartitionKSubsets(self, A, k): n, val = len(A), sum(A) / k if val != floor(val): return False A.sort() def btrack(i, space, k): if k == 1: return True for j in range(i, n): if val >= A[j] > space: break if j > i and A[j] == A[j-1] or A[j] > val: continue num, A[j] = A[j], val + 1 if num == space: if btrack(0, val, k-1): return True if btrack(j + 1, space - num, k): return True A[j] = num return False return btrack(0, val, k)
partition-to-k-equal-sum-subsets
Python3 Solution | Backtracking
satyam2001
0
189
partition to k equal sum subsets
698
0.408
Medium
11,542
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2292308/Python-backtracking-solution-with-memo
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if k > len(nums): return False if (sum(nums) % k != 0): return False # hashmap: int -> bool memo = {} # binary used as bool array(used[]) to indicate if nums[i] has been placed in a subset used = 0 # target sum of a subset target = sum(nums)/k def backtrack(k, currPath, nums, start, used, target): if (k == 0): return True if (sum(currPath) == target): res = backtrack(k-1, [], nums, 0, used, target) memo[used] = res return res # if the current permutation occurs, used the cached result instead of re-calculating if (used in memo): return memo[used] for i in range(start, len(nums)): # if current number is already in a subset if (used >> i &amp; 1) == 1: continue if (nums[i] + sum(currPath) > target): continue # set the used[i] to true using or used = used | (1 << i) # set the i position to 1 # append nums[i] to the current subset currPath.append(nums[i]) if (backtrack(k, currPath, nums, i+1, used, target)): return True # pop nums[i] from the current subset currPath.pop() # set the used[i] to false using xor used = used ^ (1 << i) return False return backtrack(k, [], nums, 0, used, target)
partition-to-k-equal-sum-subsets
Python backtracking solution with memo
leqinancy
0
51
partition to k equal sum subsets
698
0.408
Medium
11,543
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/2073591/Python3-DP-Solution
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: n, expected_sum = len(nums), sum(nums) / k nums.sort(reverse=True) if expected_sum != int(expected_sum) or nums[0] > expected_sum: return False def btrack(pos, target, done): if done == k-1: return True if pos == n: return False num = nums[pos] if num > target: return btrack(pos + 1, target, done) nums[pos] = expected_sum + 1 if num == target: return btrack(0, expected_sum, done + 1) if btrack(pos + 1, target - num, done): return True nums[pos] = num return btrack(pos + 1, target, done) return btrack(0, expected_sum, 0)
partition-to-k-equal-sum-subsets
Python3 DP Solution
TongHeartYes
0
168
partition to k equal sum subsets
698
0.408
Medium
11,544
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1962631/Python3-Backtracking-%2B-Memoization-%2B-Bit-Masking-(Detailed-Explanation)
class Solution: def canPartitionKSubsets(self, nums: List[int], K: int) -> bool: T = sum(nums) if T%K: return False N = len(nums) T = T//K taken = [False]*N d={} def helper(S,K,curr): # Base case if K==0: return True if S>T: return False if d.get((S,curr),None)!=None: return d[(S,curr)] if S==T: d[(S,curr)] = helper(0,K-1,curr) return d[(S,curr)] # Choice for i in range(len(nums)): if not taken[i]: taken[i]=True temp = curr curr = curr | 1<<i if helper(S+nums[i],K,curr): d[(S,curr)] = True return d[(S,curr)] curr=temp taken[i]=False d[(S,curr)] = False return d[(S,curr)] ans = helper(0,K,0) return ans
partition-to-k-equal-sum-subsets
Python3 Backtracking + Memoization + Bit Masking (Detailed Explanation)
KiranRaghavendra
0
159
partition to k equal sum subsets
698
0.408
Medium
11,545
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1886213/Python3-Backtracking-with-memo
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if k > len(nums): return False if (sum(nums) % k != 0): return False memo = {} used = 0 target = sum(nums)/k def backtrack(k, currPath, nums, start, used, target): if (k == 0): return True if (sum(currPath) == target): res = backtrack(k-1, [], nums, 0, used, target) memo[used] = res return res if (used in memo): return memo[used] for i in range(start, len(nums)): if (used >> i &amp; 1) == 1: continue if (nums[i] + sum(currPath) > target): continue used = used | (1 << i) # set the i position to 1 currPath.append(nums[i]) if (backtrack(k, currPath, nums, i+1, used, target)): return True currPath.pop() used = used ^ (1 << i) return False return backtrack(k, [], nums, 0, used, target)
partition-to-k-equal-sum-subsets
[Python3] Backtracking with memo
leqinancy
0
60
partition to k equal sum subsets
698
0.408
Medium
11,546
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1813800/Python-or-Still-Confusing
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: # There are k buckets bucket = [0] * k # Target sum in each bucket target = sum(nums) / k nums.sort(reverse=True) def backtrack(num, index, bucket, target): # When the process reach the end of the decision tree. if index == len(num): for i in range(len(bucket)): # Check if every bucket saisfied the target if bucket[i] != target: return False return True for i in range(len(bucket)): if bucket[i] + num[index] > target: continue bucket[i] += num[index] if backtrack(num, index + 1, bucket, target): return True bucket[i] -= num[index] return False return backtrack(nums, 0, bucket, target)
partition-to-k-equal-sum-subsets
Python | Still Confusing
Fayeyf
0
59
partition to k equal sum subsets
698
0.408
Medium
11,547
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1728529/python-using-backtracking-and-memoization
class Solution: def canPartitionKSubsets(self, matchsticks: List[int], k: int) -> bool: s = 0 n = 0 vis = [] for i in matchsticks: s = s + i n = n + 1 vis.append('0') if(s%k): return False s = s//k matchsticks.sort(reverse = True) if(matchsticks[0] > s): return False h = {} def solve(index,cur_sum,k): val = "".join(vis) if(val in h): return h[val] if(k==0): h[val] = True return True if(cur_sum == s): t = solve(0,0,k-1) h[val] = t return t for i in range(index,n): if(vis[i] != '1' and not (cur_sum + matchsticks[i] > s)): vis[i] = '1' val = "".join(vis) t = solve(i+1,cur_sum + matchsticks[i],k) h[val] = t if(t): return True vis[i] = '0' h[val] = False return False return solve(0,0,k)
partition-to-k-equal-sum-subsets
python using backtracking and memoization
jagdishpawar8105
0
245
partition to k equal sum subsets
698
0.408
Medium
11,548
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1705743/698-Partition-to-K-Equal-Sum-Subsets-via-Backtracking
class Solution: def canPartitionKSubsets(self, nums, k): if sum(nums) % k != 0: return False bucket = [0] * k target = sum(nums) / k nums.sort(reverse = True) return self.dfs(nums, k, bucket, target, 0) def dfs(self, nums, k, bucket, target, i): if i == len(nums): for ele in bucket: if ele != target: return False return True for b in range(k): if bucket[b] + nums[i] <= target: bucket[b] += nums[i] if self.dfs(nums, k, bucket, target, i + 1): return True bucket[b] -= nums[i] return False
partition-to-k-equal-sum-subsets
698 Partition to K Equal Sum Subsets via Backtracking
zwang198
0
104
partition to k equal sum subsets
698
0.408
Medium
11,549
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1705743/698-Partition-to-K-Equal-Sum-Subsets-via-Backtracking
class Solution: def canPartitionKSubsets(self, nums, k): if sum(nums) % k != 0: return False bucket = [0] * k target = sum(nums) / k nums.sort(reverse = True) return self.dfs(nums, k, bucket, target, 0, 0) def dfs(self, nums, k, bucket, target, b, iStart): if b == k - 1: return True if bucket[b] == target: return self.dfs(nums, k, bucket, target, b + 1, 0) for i in range(iStart, len(nums)): if nums[i] != "*" and bucket[b] + nums[i] <= target: bucket[b] += nums[i] temp, nums[i] = nums[i], "*" if self.dfs(nums, k, bucket, target, b, i + 1): return True nums[i] = temp bucket[b] -= nums[i] return False
partition-to-k-equal-sum-subsets
698 Partition to K Equal Sum Subsets via Backtracking
zwang198
0
104
partition to k equal sum subsets
698
0.408
Medium
11,550
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1624376/Python-FAST-method-using-dictionary-explained
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: # basic check if answer is possible in this case if sum(nums) % k > 0: return False target = sum(nums) / k if max(nums) > target: return False # start adding numbers and store current possible total numbers in dictionary keys sums = {0:[]} nums.sort(reverse=True) brk = False # for double break from the loop when target is meet while k > 0: # everytime target is met, k minus 1 # When it runs the last cycle, just check the remaining sum equals target or not if k == 1 and sum(nums) == target: return True elif k == 1: return False # loop through the biggest number to the smallest for n in nums.copy(): if brk: # if target is met then go to next round brk = False break # loop through all possible combinations keys = list(sums.keys()) for key in keys: ans = key + n if ans == target: # remove all used numbers from nums nums.remove(n) for m in sums[key]: nums.remove(m) # reset sums dictionary and minus k by 1 k -= 1 sums.clear() sums[0] = [] brk = True break elif ans > target: continue elif ans not in sums: sums[ans] = sums[key]+[n] # if the dictionary is not reset means no possible answer founded if len(sums.keys()) > 1: return False
partition-to-k-equal-sum-subsets
Python FAST method using dictionary explained
PoHandsome
0
199
partition to k equal sum subsets
698
0.408
Medium
11,551
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1511412/Python-simple-backtracking-solution-(easy-to-understand)
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: s = sum(nums) if s % k != 0: return False target = s // k n = len(nums) def dfs(m): stack = [(m, 0, {m}, nums[m])] while stack: #print(stack) node, cnt, path, sums = stack.pop() if sums == target: if cnt == k-1: return True for i in range(0, n): if i not in path: stack.append((i, cnt+1, path | {i}, nums[i])) elif sums < target: for i in range(node+1, n): if i not in path: stack.append((i, cnt, path | {i}, sums + nums[i])) else: # sums > target pass return False return dfs(0)
partition-to-k-equal-sum-subsets
Python simple backtracking solution (easy to understand)
byuns9334
0
282
partition to k equal sum subsets
698
0.408
Medium
11,552
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1364360/Python-Code-or-90-Faster
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: s=sum(nums) if s%k !=0 or not nums or len(nums)==0: return False self.tar=s//k nums.sort(reverse=True) self.k=k self.seen=[] def dfs(nums,start,group,curr): if group==self.k: return True if curr==self.tar: return dfs(nums,0,group+1,0) if curr>self.tar: return False for i in range (start,len(nums)): if i in self.seen: continue self.seen.append(i) if dfs(nums,i+1,group,curr+nums[i]): return True self.seen.pop() return dfs(nums,0,0,0)
partition-to-k-equal-sum-subsets
Python Code | 90% Faster
rackle28
0
231
partition to k equal sum subsets
698
0.408
Medium
11,553
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/904900/Python3-backtracking
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) if total % k: return False avg = total // k sm = [0]*k nums.sort(reverse=True) def fn(i): """Return True if possible to partition.""" if i == len(nums): return True for kk in range(k): if sm[kk] + nums[i] <= avg: sm[kk] += nums[i] if fn(i+1): return True sm[kk] -= nums[i] if sm[kk] == 0: break return False return fn(0)
partition-to-k-equal-sum-subsets
[Python3] backtracking
ye15
0
147
partition to k equal sum subsets
698
0.408
Medium
11,554
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/904900/Python3-backtracking
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: total = sum(nums) if total % k: return False avg = total // k @cache def fn(x, mask): """Return True if available elements can be parititioned.""" if x > avg: return False if x == avg: return fn(0, mask) if not mask: return True for i in range(len(nums)): if mask &amp; 1<<i and fn(x + nums[i], mask ^ 1<<i): return True return False nums.sort(reverse=True) return fn(0, (1 << len(nums))-1)
partition-to-k-equal-sum-subsets
[Python3] backtracking
ye15
0
147
partition to k equal sum subsets
698
0.408
Medium
11,555
https://leetcode.com/problems/falling-squares/discuss/2397036/faster-than-90.37-or-python-or-solution-or-explained
class Solution: def fallingSquares(self, positions): height, pos, max_h,res = [0],[0],0,[] for left, side in positions: i = bisect.bisect_right(pos, left) j = bisect.bisect_left(pos, left + side) high = max(height[i - 1:j] or [0]) + side pos[i:j] = [left, left + side] height[i:j] = [high, height[j - 1]] max_h = max(max_h, high) res.append(max_h) return res
falling-squares
faster than 90.37% | python | solution | explained
vimla_kushwaha
1
57
falling squares
699
0.444
Hard
11,556
https://leetcode.com/problems/falling-squares/discuss/1494448/Python3-brute-force
class Solution: def fallingSquares(self, positions: List[List[int]]) -> List[int]: ans = [] for i, (x, l) in enumerate(positions): val = 0 for ii in range(i): xx, ll = positions[ii] if xx < x+l and x < xx+ll: val = max(val, ans[ii]) ans.append(val + l) for i in range(1, len(ans)): ans[i] = max(ans[i-1], ans[i]) return ans
falling-squares
[Python3] brute-force
ye15
0
51
falling squares
699
0.444
Hard
11,557
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/943397/Python-Simple-Solution
class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return if root.val==val: return root if root.val<val: return self.searchBST(root.right,val) else: return self.searchBST(root.left,val)
search-in-a-binary-search-tree
Python Simple Solution
lokeshsenthilkumar
20
1,300
search in a binary search tree
700
0.772
Easy
11,558
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1944884/Simple-5-Line-Python-Code
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val == val: # If end is reached or a node with a value of target is found found. return root # Return that node. # If target > current nodes value search in left side of node else search rightwards. return self.searchBST(root.left,val) if root.val > val else self.searchBST(root.right,val)
search-in-a-binary-search-tree
Simple 5 Line Python Code
anCoderr
12
991
search in a binary search tree
700
0.772
Easy
11,559
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1944884/Simple-5-Line-Python-Code
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: return root if not root or root.val == val else self.searchBST(root.left if root.val > val else root.right, val)
search-in-a-binary-search-tree
Simple 5 Line Python Code
anCoderr
12
991
search in a binary search tree
700
0.772
Easy
11,560
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1046218/Python.-Super-simple-and-clear-solution.-iterative.-5-lines.
class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: while root: if val < root.val: root = root.left elif val > root.val: root = root.right else: return root return root
search-in-a-binary-search-tree
Python. Super simple & clear solution. iterative. 5 lines.
m-d-f
5
299
search in a binary search tree
700
0.772
Easy
11,561
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2180667/Python3-Binary-search-faster-than-96
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: def search(root): if root == None: return None if root.val == val: return root if val < root.val: return search(root.left) else: return search(root.right) return search(root)
search-in-a-binary-search-tree
📌 Python3 Binary search faster than 96%
Dark_wolf_jss
4
50
search in a binary search tree
700
0.772
Easy
11,562
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1944579/Python3-oror-Simple-3-lines
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root or root.val == val: return root return self.searchBST(root.left, val) if val < root.val else self.searchBST(root.right, val)
search-in-a-binary-search-tree
✔️ Python3 || Simple 3 lines
constantine786
4
289
search in a binary search tree
700
0.772
Easy
11,563
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1944579/Python3-oror-Simple-3-lines
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root and root.val != val: root = root.left if val < root.val else root.right return root
search-in-a-binary-search-tree
✔️ Python3 || Simple 3 lines
constantine786
4
289
search in a binary search tree
700
0.772
Easy
11,564
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2508885/Python-Elegant-and-Short-or-Two-solutions-or-Iterative-and-Recursive-or-Three-lines
class Solution: """ Time: O(n) Memory: O(1) """ def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root is not None and root.val != val: root = root.left if val < root.val else root.right return root class Solution: """ Time: O(n) Memory: O(n) """ def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val == val: return root return self.searchBST(root.left if val < root.val else root.right, val)
search-in-a-binary-search-tree
Python Elegant & Short | Two solutions | Iterative & Recursive | Three lines
Kyrylo-Ktl
2
144
search in a binary search tree
700
0.772
Easy
11,565
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2207822/Python-3-or-89ms-or-Recursion
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return elif root.val==val: return root elif root.val > val: return self.searchBST(root.left, val) else: return self.searchBST(root.right, val)
search-in-a-binary-search-tree
Python 3 | 89ms | Recursion
yashpurohit763
1
62
search in a binary search tree
700
0.772
Easy
11,566
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1520987/python3-intuitive-solution
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root or val == root.val: # base case return root # recurrence relation return self.searchBST(root.left if val < root.val else root.right, val)
search-in-a-binary-search-tree
python3 intuitive solution
feexon
1
68
search in a binary search tree
700
0.772
Easy
11,567
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1520987/python3-intuitive-solution
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root: if val == root.val: return root root = root.left if val < root.val else root.right
search-in-a-binary-search-tree
python3 intuitive solution
feexon
1
68
search in a binary search tree
700
0.772
Easy
11,568
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1032317/Python3-easy-solution
class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: bfs = [root] while bfs: node = bfs.pop(0) if node.val == val: return node if node.left: bfs.append(node.left) if node.right: bfs.append(node.right) return None
search-in-a-binary-search-tree
Python3 easy solution
EklavyaJoshi
1
111
search in a binary search tree
700
0.772
Easy
11,569
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1032317/Python3-easy-solution
class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return None if root.val == val: return root elif root.val > val: return self.searchBST(root.left,val) elif root.val < val: return self.searchBST(root.right,val)
search-in-a-binary-search-tree
Python3 easy solution
EklavyaJoshi
1
111
search in a binary search tree
700
0.772
Easy
11,570
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2834410/Python-or-Search-in-BST-or-simple-code-with-detailed-explanation
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root == None: return None if root.val == val: return root elif root.val > val: return self.searchBST(root.left,val) else: return self.searchBST(root.right,val)
search-in-a-binary-search-tree
Python | Search in BST | simple code with detailed explanation
utkarshjain
0
4
search in a binary search tree
700
0.772
Easy
11,571
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2794746/Super-easy-python-solutiopn
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return None if root.val == val: return root return self.searchBST(root.left,val) or self.searchBST(root.right,val)
search-in-a-binary-search-tree
Super easy python solutiopn
betaal
0
1
search in a binary search tree
700
0.772
Easy
11,572
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2730523/Recursive-%2B-Iterative
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return None if root.val == val: return root if root.val < val: return self.searchBST(root.right, val) else: return self.searchBST(root.left, val)
search-in-a-binary-search-tree
Recursive + Iterative
hacktheirlives
0
1
search in a binary search tree
700
0.772
Easy
11,573
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2730523/Recursive-%2B-Iterative
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root is not None and root.val != val: root = root.left if val < root.val else root.right return root
search-in-a-binary-search-tree
Recursive + Iterative
hacktheirlives
0
1
search in a binary search tree
700
0.772
Easy
11,574
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2707070/94-Accepted-Solution-or-Easy-to-Understand-or-Python
class Solution(object): def searchBST(self, root, val): q = deque() q.append(root) while q: for _ in range(len(q)): p = q.popleft() if p.val == val: return p if p.left: q.append(p.left) if p.right: q.append(p.right) return None
search-in-a-binary-search-tree
94% Accepted Solution | Easy to Understand | Python
its_krish_here
0
3
search in a binary search tree
700
0.772
Easy
11,575
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2688447/python-or-easy-solution
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return None if root.val == val: return root if root.val < val: return self.searchBST(root.right, val) if root.val > val: return self.searchBST(root.left, val) return None
search-in-a-binary-search-tree
python | easy solution
MichelleZou
0
10
search in a binary search tree
700
0.772
Easy
11,576
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2681514/Python-3-Solution-(Recursion)
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root: if root.val == val: return root elif val > root.val: return (self.searchBST(root.right,val)) elif val < root.val: return (self.searchBST(root.left,val)) else: return root
search-in-a-binary-search-tree
Python 3 Solution (Recursion)
rahulnakum
0
16
search in a binary search tree
700
0.772
Easy
11,577
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2565867/Python-or-BFS-or-Faster-than-98.30
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: q = deque() q.append(root) while q: node = q.popleft() # print(node.val) if node.val == val: return node elif val < node.val and node.left: q.append(node.left) elif val > node.val and node.right: q.append(node.right) return None
search-in-a-binary-search-tree
Python | BFS | Faster than 98.30%
ckayfok
0
26
search in a binary search tree
700
0.772
Easy
11,578
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2336516/Python-Simple-Iterative-S-O(1)-and-Recursive-oror-Documented
class Solution: # Recursive: T = O(log N) and S = O(log N) for stack created recursively def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return None # if target value matched, return root if root.val == val: return root # if target val is smaller, check in left subtree if val < root.val: return self.searchBST(root.left, val) # else check in right sub tree return self.searchBST(root.right, val) # Iterative: T = O(log N) and S = O(1) def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root: if root.val == val: return root # go left if target val is less than cur val, else go right root = root.left if val < root.val else root.right return None
search-in-a-binary-search-tree
[Python] Simple Iterative S = O(1) and Recursive || Documented
Buntynara
0
10
search in a binary search tree
700
0.772
Easy
11,579
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2276178/Python3-65ms-faster-than-99.52
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root == None: return None if root.val == val: return root return self.searchBST(root.left, val) or self.searchBST(root.right, val)
search-in-a-binary-search-tree
Python3 - 65ms - faster than 99.52%
spjoshis
0
57
search in a binary search tree
700
0.772
Easy
11,580
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2222900/Python-simple-solution
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root: if root.val == val: return root root = root.left if root.val > val else root.right
search-in-a-binary-search-tree
Python simple solution
meatcodex
0
5
search in a binary search tree
700
0.772
Easy
11,581
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2153313/Python3-Solution
class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root or root.val == val: return root if root.val < val: #要是目标值比根节点大 则在右子树中寻找 return self.searchBST(root.right, val) if root.val > val: #要是目标值比根节点小 则在左子树中寻找 return self.searchBST(root.left, val)
search-in-a-binary-search-tree
Python3 Solution
qywang
0
33
search in a binary search tree
700
0.772
Easy
11,582
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/2033083/Python-Simple-readable-easy-to-understand-recursive-solution-(77-ms)
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root: if root.val == val: return root elif root.val > val: return self.searchBST(root.left, val) else: return self.searchBST(root.right, val)
search-in-a-binary-search-tree
[Python] Simple, readable, easy to understand, recursive solution (77 ms)
FedMartinez
0
47
search in a binary search tree
700
0.772
Easy
11,583
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1960569/Python-iterative-3-lines-of-code.-No-recursion-O(1)-Space-O(nlogn)-average-time.
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root and root.val != val: root = root.left if root.val > val else root.right return root
search-in-a-binary-search-tree
Python iterative 3 lines of code. No recursion, O(1) Space, O(n·logn) average time.
sEzio
0
42
search in a binary search tree
700
0.772
Easy
11,584
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1947577/python-3-oror-simple-iterative-solution
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root: if val == root.val: return root elif val < root.val: root = root.left else: root = root.right
search-in-a-binary-search-tree
python 3 || simple iterative solution
dereky4
0
12
search in a binary search tree
700
0.772
Easy
11,585
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1947357/Simple-python3-Solution
class Solution(object): def searchBST(self, root, val): trav = root while trav: if trav.val == val: return trav elif trav.val < val: trav = trav.right else: trav = trav.left
search-in-a-binary-search-tree
Simple python3 Solution
nomanaasif9
0
11
search in a binary search tree
700
0.772
Easy
11,586
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1947127/Python-Recursive-%2B-Iterative-%2B-Bonus%3A-One-Liner!
class Solution: def searchBST(self, root, val): if not root: return None elif root.val > val: return self.searchBST(root.left, val) elif root.val < val: return self.searchBST(root.right, val) else: return root
search-in-a-binary-search-tree
Python - Recursive + Iterative + Bonus: One-Liner!
domthedeveloper
0
18
search in a binary search tree
700
0.772
Easy
11,587
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1947127/Python-Recursive-%2B-Iterative-%2B-Bonus%3A-One-Liner!
class Solution: def searchBST(self, root, val): return None if not root else self.searchBST(root.left, val) if root.val > val else self.searchBST(root.right, val) if root.val < val else root
search-in-a-binary-search-tree
Python - Recursive + Iterative + Bonus: One-Liner!
domthedeveloper
0
18
search in a binary search tree
700
0.772
Easy
11,588
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1947127/Python-Recursive-%2B-Iterative-%2B-Bonus%3A-One-Liner!
class Solution: def searchBST(self, root, val): stack = [root] while stack: node = stack.pop() if not node: return None elif node.val > val: stack.append(node.left) elif node.val < val: stack.append(node.right) else: return node
search-in-a-binary-search-tree
Python - Recursive + Iterative + Bonus: One-Liner!
domthedeveloper
0
18
search in a binary search tree
700
0.772
Easy
11,589
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1946834/Python-Fast-Recursive-Solution-No-Memory-Used
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: while root and root.val != val: root = root.left if val < root.val else root.right return root
search-in-a-binary-search-tree
Python Fast Recursive Solution, No Memory Used
Hejita
0
14
search in a binary search tree
700
0.772
Easy
11,590
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1946088/Python-or-Recursion-or-Beats-99.7
class Solution(object): def searchBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ def search(node, val): op = None if node.val == val: op = node elif node.val > val and node.left: op = search(node.left, val) elif node.val < val and node.right: op = search(node.right, val) return op return search(root, val)
search-in-a-binary-search-tree
Python | Recursion | Beats 99.7%
prajyotgurav
0
13
search in a binary search tree
700
0.772
Easy
11,591
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1945657/Python-solution-92-faster
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[ TreeNode]: while root: if root.val == val: return root if root.val < val: root = root.right else: root = root.left return root
search-in-a-binary-search-tree
Python solution 92% faster
pradeep288
0
14
search in a binary search tree
700
0.772
Easy
11,592
https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/1945344/Python3-Solution-with-using-recursive-dfs
class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return None if root.val == val: return root return self.searchBST(root.left, val) or self.searchBST(root.right, val)
search-in-a-binary-search-tree
[Python3] Solution with using recursive dfs
maosipov11
0
7
search in a binary search tree
700
0.772
Easy
11,593
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1683883/Python3-ITERATIVE-(-)-Explained
class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return TreeNode(val) cur, next = None, root while next: cur = next next = cur.left if val < cur.val else cur.right if val < cur.val: cur.left = TreeNode(val) else: cur.right = TreeNode(val) return root
insert-into-a-binary-search-tree
✔️ [Python3] ITERATIVE (づ ̄ ³ ̄)づ ❤, Explained
artod
26
1,300
insert into a binary search tree
701
0.746
Medium
11,594
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1683964/Python-or-Simple-Recursive-or-Clean-or-O(N)-Timeor-O(1)-Space
class Solution: def insertIntoBST(self, root, val): if not root: return TreeNode(val) if val<root.val: root.left = self.insertIntoBST(root.left, val) else: root.right = self.insertIntoBST(root.right, val) return root
insert-into-a-binary-search-tree
[Python] | Simple Recursive | Clean | O(N) Time| O(1) Space
matthewlkey
9
459
insert into a binary search tree
701
0.746
Medium
11,595
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2180670/Python3-recursive-solution
class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root == None: return TreeNode(val) def insert(root): if root == None: return TreeNode(val) if val < root.val: if root.left: insert(root.left) else: root.left = insert(root.left) else: if root.right: insert(root.right) else: root.right = insert(root.right) insert(root) return root
insert-into-a-binary-search-tree
📌 Python3 recursive solution
Dark_wolf_jss
4
28
insert into a binary search tree
701
0.746
Medium
11,596
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/305489/Python3-Iterative-solution
class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: cur_node = root while True: if val > cur_node.val: if cur_node.right == None: cur_node.right = TreeNode(val) break else: cur_node = cur_node.right if val < cur_node.val: if cur_node.left == None: cur_node.left = TreeNode(val) break else: cur_node = cur_node.left return root
insert-into-a-binary-search-tree
Python3 Iterative solution
decimalst
2
109
insert into a binary search tree
701
0.746
Medium
11,597
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1994441/Python-oror-Simple-Iterative-Solution
class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: new, origin = TreeNode(val), root if not root: return new while root: prev = root if val > root.val: root = root.right else: root = root.left if val > prev.val: prev.right = new else: prev.left = new return origin
insert-into-a-binary-search-tree
Python || Simple Iterative Solution
morpheusdurden
1
56
insert into a binary search tree
701
0.746
Medium
11,598
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1684033/Python-3-Recursive-simple-O(n)-Explained
class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: def searchPlaceAndInsert(root,val): if val < root.val: if root.left: searchPlaceAndInsert(root.left, val) else: root.left = TreeNode(val) else: if root.right: searchPlaceAndInsert(root.right, val) else: root.right = TreeNode(val) if not root: return TreeNode(val) searchPlaceAndInsert(root, val) return root
insert-into-a-binary-search-tree
👩‍💻 Python 3 Recursive simple O(n) Explained
letyrodri
1
19
insert into a binary search tree
701
0.746
Medium
11,599