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/remove-outermost-parentheses/discuss/1979748/python-3-oror-simple-solution-oror-O(n)O(1)
class Solution: def removeOuterParentheses(self, s: str) -> str: res = [] curOpen = 0 for c in s: if c == '(': if curOpen: res.append(c) curOpen += 1 else: curOpen -= 1 if curOpen: res.append(c) return ''.join(res)
remove-outermost-parentheses
python 3 || simple solution || O(n)/O(1)
dereky4
1
207
remove outermost parentheses
1,021
0.802
Easy
16,700
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1741388/Python3-solution-using-stack!
class Solution: def removeOuterParentheses(self, s: str) -> str: stack = [] res = "" for item in s : if item == "(" : if len(stack) > 0: res += item stack.append(item) else : stack.pop() if len(stack) > 0: res += item return res
remove-outermost-parentheses
Python3 solution using stack!
shakilbabu
1
94
remove outermost parentheses
1,021
0.802
Easy
16,701
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1709610/Understandable-code-for-beginners-like-me-in-python-!!
class Solution: def removeOuterParentheses(self, s: str) -> str: counter=1 slen=len(s) decomposedlist=[] start=0 for index in range(1,slen): if(s[index]=="("): counter+=1 else: counter-=1 if(counter==0): decomposedlist.append(s[start+1:index]) start=index+1 s=''.join(decomposedlist) return s
remove-outermost-parentheses
Understandable code for beginners like me in python !!
kabiland
1
47
remove outermost parentheses
1,021
0.802
Easy
16,702
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1657907/Simple-Logic-Using-Stack
class Solution: def removeOuterParentheses(self, s: str) -> str: if s=="": return "" l=[] x=0 ans="" for i in range(len(s)): if s[i]=="(": l.append(s[i]) else: l.pop() if l==[]: ans+=s[x+1:i] x=i+1 return ans
remove-outermost-parentheses
Simple Logic Using Stack
gamitejpratapsingh998
1
163
remove outermost parentheses
1,021
0.802
Easy
16,703
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1657907/Simple-Logic-Using-Stack
class Solution: def removeOuterParentheses(self, s: str) -> str: if s=="": return "" l=[] x=y=0 ans="" for i in range(len(s)): if s[i]=="(": l.append(s[i]) else: l.pop() if l==[]: x,y=i+1,i if x!=i and y!=i: ans+=s[i] return ans
remove-outermost-parentheses
Simple Logic Using Stack
gamitejpratapsingh998
1
163
remove outermost parentheses
1,021
0.802
Easy
16,704
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1412725/Runtime%3A-32-ms-faster-than-92.32-of-Python3-online-submissions
class Solution: def removeOuterParentheses(self, s: str) -> str: c=0 res="" for i in s: if c==0 and i=="(": c+=1 elif c!=0 and i=="(": res+=i c+=1 elif c!=1 and i==")": res+=i c-=1 else: c-=1 return res
remove-outermost-parentheses
Runtime: 32 ms, faster than 92.32% of Python3 online submissions
harshmalviya7
1
104
remove outermost parentheses
1,021
0.802
Easy
16,705
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1291578/Easy-Python-Solution(93.19)
class Solution: def removeOuterParentheses(self, s: str) -> str: c=0 stack=[] for i in range(len(s)): if(s[i]=="(" and c!=0): stack.append(s[i]) c+=1 elif(s[i]==")" and c!=1): stack.append(s[i]) c-=1 elif(s[i]=="(" and c==0): c+=1 else: c-=1 return "".join(stack)
remove-outermost-parentheses
Easy Python Solution(93.19%)
Sneh17029
1
464
remove outermost parentheses
1,021
0.802
Easy
16,706
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1125978/Python-3-Very-Easy-and-83-Fast-Solution
class Solution: def removeOuterParentheses(self, S: str) -> str: COUNT = 0 START = 0 RES = '' for i in range(len(S)): if (S[i] == '('): COUNT += 1 else: COUNT -= 1 if COUNT == 0: RES += S[START+1 : i] START += i+1 return RES
remove-outermost-parentheses
Python 3 - Very Easy and 83% Fast Solution
piyushagg19
1
131
remove outermost parentheses
1,021
0.802
Easy
16,707
https://leetcode.com/problems/remove-outermost-parentheses/discuss/961003/Python-Easy-to-read-O(n)
class Solution: def removeOuterParentheses(self, S: str) -> str: depth = 0 out_str = "" for c in S: if c == '(': if depth > 0: out_str += '(' depth += 1 else: depth -= 1 if depth > 0: out_str += ')' return out_str
remove-outermost-parentheses
[Python] Easy to read O(n)
llai
1
78
remove outermost parentheses
1,021
0.802
Easy
16,708
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2843188/Python-Solution
class Solution: def removeOuterParentheses(self, s: str) -> str: s_list = list(s) count = 0 for idx, element in enumerate(s): if element == "(": count += 1 if count == 1: s_list[idx] = "pop" else: count -= 1 if count == 0: s_list[idx] = "pop" s = "".join(s_list) s = s.replace("pop", "") return s
remove-outermost-parentheses
Python Solution
corylynn
0
3
remove outermost parentheses
1,021
0.802
Easy
16,709
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2806301/simple-python-solution-oror-O(N)-Time-complexity
class Solution: def removeOuterParentheses(self, s: str) -> str: ans,count="",0 for i in s: count+=1 if i=='(' else -1 if count>1 or (count==1 and i==')'): ans+=i return ans
remove-outermost-parentheses
simple python solution || O(N) Time complexity
Nikhil2532
0
4
remove outermost parentheses
1,021
0.802
Easy
16,710
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2799812/Python3-solution-with-iteration-and-pop
class Solution: def removeOuterParentheses(self, s: str) -> str: s = list(s) level = 0 i = 0 while i < len(s): if s[i] == "(": if level == 0: s.pop(i) i -= 1 level += 1 else: level -= 1 if level == 0: s.pop(i) i -= 1 i += 1 return "".join(s)
remove-outermost-parentheses
Python3 solution with iteration and pop
sipi09
0
1
remove outermost parentheses
1,021
0.802
Easy
16,711
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2782359/Solution
class Solution: def removeOuterParentheses(self, s: str) -> str: primitives = [] pointer = 0 temp = [] for i in s: temp.append(i) if i == "(": pointer+=1 elif i == ")": pointer -= 1 if pointer == 0: primitives.append("".join(temp)) temp = [] return ''.join([x[1:-1] for x in primitives])
remove-outermost-parentheses
Solution
labdhi_shah_5400
0
1
remove outermost parentheses
1,021
0.802
Easy
16,712
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2780896/Python-Solution-or-90-Faster-or-Stack-and-No-Stack-Based
class Solution: def removeOuterParentheses(self, s: str) -> str: store = [] start = 0 ans = [] for curr,char in enumerate(s): if store and store[-1] == "(" and char == ")": store.pop(-1) if not store: ans.append(s[start+1:curr]) start = curr + 1 else: store.append(char) return ''.join(ans)
remove-outermost-parentheses
Python Solution | 90% Faster | Stack and No Stack Based
Gautam_ProMax
0
7
remove outermost parentheses
1,021
0.802
Easy
16,713
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2780896/Python-Solution-or-90-Faster-or-Stack-and-No-Stack-Based
class Solution: def removeOuterParentheses(self, s: str) -> str: store = 0 start = 0 ans = [] for curr,char in enumerate(s): if char == "(": store += 1 if char == ")": store -= 1 if store == 0: ans.append(s[start+1:curr]) start = curr + 1 return ''.join(ans)
remove-outermost-parentheses
Python Solution | 90% Faster | Stack and No Stack Based
Gautam_ProMax
0
7
remove outermost parentheses
1,021
0.802
Easy
16,714
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2779120/Python-One-Line
class Solution: def removeOuterParentheses(self, s: str) -> str: return (lambda prefix : "".join(s[i] for i in range(len(s)) if prefix[i] != 0 and prefix[i+1] != 0))(list(accumulate(map(lambda x : 1 if x == "(" else -1, s), initial=0)))
remove-outermost-parentheses
Python One Line
Norelaxation
0
3
remove outermost parentheses
1,021
0.802
Easy
16,715
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2269502/Python3-Simple-Solution
class Solution: def removeOuterParentheses(self, s: str) -> str: stack = [] ans = "" counter = 0 for x in s : if x == "(" : stack.append(x) counter += 1 if counter > 1 : ans += "(" if x == ")" : stack.pop(-1) counter -= 1 if counter > 0 : ans += ")" return ans
remove-outermost-parentheses
Python3 Simple Solution
jasoriasaksham01
0
59
remove outermost parentheses
1,021
0.802
Easy
16,716
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2259603/Python-STack
class Solution(object): def removeOuterParentheses(self, s): from collections import deque def solve(s): ans = '' basket = '' stack = deque() for ch in s: if ch!=')': stack.append(ch) elif ch ==')': stack.pop() basket+=ch if not stack: ans+=basket[1:-1] basket = '' return ans return solve(s)
remove-outermost-parentheses
Python STack
Abhi_009
0
53
remove outermost parentheses
1,021
0.802
Easy
16,717
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1907905/Python-easy-to-read-and-understand-or-simulation
class Solution: def removeOuterParentheses(self, s: str) -> str: temp, res = "", "" stack = [] for i in range(len(s)): if s[i] == "(": stack.append(s[i]) elif s[i] == ")": stack.pop() if len(stack) > 1 or (stack and s[i] == ")"): temp += s[i] if len(stack) == 0: res += temp temp = "" return res
remove-outermost-parentheses
Python easy to read and understand | simulation
sanial2001
0
120
remove outermost parentheses
1,021
0.802
Easy
16,718
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1755813/Python-Easy-Solution%3A-beats-85
class Solution: def removeOuterParentheses(self, s: str) -> str: ans = '' stack = [] temp = '' for ch in s: if ch == '(': stack.append(ch) temp+='(' elif ch == ')': c = stack.pop() temp += ch if not stack: temp = temp[1:][:-1] ans += temp temp = '' return ans
remove-outermost-parentheses
Python Easy Solution: beats 85%
dos_77
0
94
remove outermost parentheses
1,021
0.802
Easy
16,719
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1724065/Python-simple-stack-solution
class Solution: def removeOuterParentheses(self, s: str) -> str: res = '' string = '' stack = [] for c in s: if c == '(': stack.append(c) else: # c == ')' if stack and stack[-1]: stack.pop() string += c if not stack: res += string[1:-1] string = '' return res
remove-outermost-parentheses
Python simple stack solution
byuns9334
0
80
remove outermost parentheses
1,021
0.802
Easy
16,720
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1706837/Python-Solution-or-faster-than-98.87
class Solution: def removeOuterParentheses(self, s: str) -> str: stack = [] var = 0 newstr = "" for i in range(len(s)): if s[i] == "(": stack.append(s[i]) else: stack.pop() if len(stack) == 0: newstr += s[var+1:i] var = i+1 return newstr
remove-outermost-parentheses
Python Solution | faster than 98.87%
vijayvardhan6
0
90
remove outermost parentheses
1,021
0.802
Easy
16,721
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1681054/Uncompressed-step-by-step-python-solution
class Solution: def removeOuterParentheses(self, s: str) -> str: collect_primitives = [] counter = 0 start = 0 end = 0 for i in range(0, len(s)): # When counter is 0, the expression is balanced. Either it indicates that a new primitive expression can start in the string, or indicates that a primtive expression has been examined. if s[i] == "(": if counter == 0: # Mark the start of primitive expression. start = i counter+=1 elif s[i] == ")": counter-=1 if counter == 0: end = i # Mark the end of primitive expression # Once a primitive expression has been read, slice the primitive expression. start plus one, because start index points to opening bracket of the pair which encloses a primitive expression. if counter == 0: collect_primitives.append(s[start + 1:end]) start = 0 end = 0 return "".join(collect_primitives)
remove-outermost-parentheses
Uncompressed, step by step python solution
snagsbybalin
0
34
remove outermost parentheses
1,021
0.802
Easy
16,722
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1308749/Python-or-Easy-and-fast-solution
class Solution: def removeOuterParentheses(self, s: str) -> str: count = 0 res = '' for i, c in enumerate(s): if c == '(': # if count == 0 it means that we deal with the outermost parentheses if count != 0: res += c count += 1 if c == ')': count -= 1 # if count == 0 it means that we deal with the outermost parentheses if count != 0: res += c return res
remove-outermost-parentheses
Python | Easy and fast solution
iaramer
0
38
remove outermost parentheses
1,021
0.802
Easy
16,723
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1241816/python-or-92-or-easy
class Solution: def removeOuterParentheses(self, S: str) -> str: m=0 last= -1 ans='' for j in range(len(S)): if S[j]=='(': if m==0: last= j m+=1 else: m-=1 if m==0: ans+=S[last+1:j] last=-1 return ans
remove-outermost-parentheses
python | 92% | easy
chikushen99
0
118
remove outermost parentheses
1,021
0.802
Easy
16,724
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1079697/easy-and-faster-oython-code
class Solution: def removeOuterParentheses(self, S: str) -> str: count,j=0,0 string='' for i in range(len(S)): if S[i]=='(': count +=1 j=min(i,j) else: count -=1 if count==0: if j>0: j=j+1 string +=S[j+1:i] j=i else: string +=S[j+1:i] j=i return string
remove-outermost-parentheses
easy and faster oython code
yashwanthreddz
0
86
remove outermost parentheses
1,021
0.802
Easy
16,725
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1054067/Super-easy-to-understand-(-NPDA-)
class Solution: def removeOuterParentheses(self, S: str) -> str: state, stack, res = 0,[], "" for i in S: if i == "(" and len(stack) == 0: stack.append(i) state = 1 elif state == 1: if i == ")" and len(stack) > 1: stack.pop() res = res + i elif i == ")" and len(stack) == 1: stack.pop() state = 0 elif i == "(" and len(stack) >= 1: stack.append(i) res = res + i return res
remove-outermost-parentheses
Super easy to understand ( NPDA )
hoyu
0
88
remove outermost parentheses
1,021
0.802
Easy
16,726
https://leetcode.com/problems/remove-outermost-parentheses/discuss/976745/Python
class Solution: def removeOuterParentheses(self, S: str) -> str: bal = 0 ret = '' j = 0 for i in range(len(S)): if S[i] == '(': if bal == 0: j = i bal += 1 elif S[i] == ')': bal -= 1 if bal == 0: ret += S[j+1:i] return ret
remove-outermost-parentheses
Python
Aditya380
0
88
remove outermost parentheses
1,021
0.802
Easy
16,727
https://leetcode.com/problems/remove-outermost-parentheses/discuss/700570/Python-3
class Solution: def removeOuterParentheses(self, S: str) -> str: x = [] count = 0 for i in S: if i == '(' and count > 0 : x.append(i) if i == ')' and count > 1 : x.append(i) # if i == '(' : # count += 1 # else: # count -= 1 if i == '(' : count += 1 else: count -= 1 return "".join(x)
remove-outermost-parentheses
Python 3
abhijeetmallick29
0
346
remove outermost parentheses
1,021
0.802
Easy
16,728
https://leetcode.com/problems/remove-outermost-parentheses/discuss/335390/Solution-in-Python-3
class Solution: def removeOuterParentheses(self, S: str) -> str: S = list(S) c, i, j = 0, 0, 0 f = {'(':1, ')':-1} while i < len(S): c += f[S[i]] if c == 0: del S[j] del S[i-1] i -= 2 j = i + 1 i += 1 return("".join(S)) - Python 3 - Junaid Mansuri
remove-outermost-parentheses
Solution in Python 3
junaidmansuri
0
510
remove outermost parentheses
1,021
0.802
Easy
16,729
https://leetcode.com/problems/remove-outermost-parentheses/discuss/288776/python3-faster-than-100
class Solution: def removeOuterParentheses(self, S: str) -> str: if not S: return '' # find the outmost Paretheses index opened = 0 result = [] left = 0 for index,item in enumerate(S): opened += 1 if item == '(' else -1 if opened == 0: result.append(S[left+1:index]) left = index +1 return "".join(result)
remove-outermost-parentheses
python3 faster than 100%
XingDongZhe
0
85
remove outermost parentheses
1,021
0.802
Easy
16,730
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1681647/Python3-5-LINES-(-)-Explained
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: def dfs(node, path): if not node: return 0 path = (path << 1) + node.val if not node.left and not node.right: return path return dfs(node.left, path) + dfs(node.right, path) return dfs(root, 0)
sum-of-root-to-leaf-binary-numbers
✔️ [Python3] 5-LINES ☜ ( ͡❛ 👅 ͡❛), Explained
artod
19
876
sum of root to leaf binary numbers
1,022
0.737
Easy
16,731
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1043156/Python3-simple-solution-using-bfs-traversal
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: bfs = [root] l = [] while bfs: node = bfs.pop(0) if node.left: x = node.left.val node.left.val = str(node.val) + str(x) bfs.append(node.left) if node.right: x = node.right.val node.right.val = str(node.val) + str(x) bfs.append(node.right) if not node.left and not node.right: l.append(str(node.val)) return sum([int(i,2) for i in l])
sum-of-root-to-leaf-binary-numbers
Python3 simple solution using bfs traversal
EklavyaJoshi
4
137
sum of root to leaf binary numbers
1,022
0.737
Easy
16,732
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1191997/PythonPython3-Sum-of-Root-To-Leaf-Binary-Numbers
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: def calc(node, temp): if not node: return 0 temp = temp*2 + node.val if (node.left is None) and (node.right is None): return temp return (calc(node.left, temp) + calc(node.right, temp)) return calc(root, 0)
sum-of-root-to-leaf-binary-numbers
[Python/Python3] Sum of Root To Leaf Binary Numbers
newborncoder
3
296
sum of root to leaf binary numbers
1,022
0.737
Easy
16,733
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1681578/Python3-DFS%2BBacktracking-solution
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: # defining a global variable for recursive helper to modify ret = [0] def helper(curr, currpath): if curr is None: return # case where leaf node has been reached if curr.left is None and curr.right is None: currpath.append(curr.val) bin_str = "".join(map(str, currpath)) ret[0] += int(bin_str, 2) currpath.pop() return # append the current node's value to the array before processing children currpath.append(curr.val) helper(curr.left, currpath) helper(curr.right, currpath) # remove the current node's value before returning to callee currpath.pop() helper(root, []) return ret[0]
sum-of-root-to-leaf-binary-numbers
Python3 DFS+Backtracking solution
lfu7
2
174
sum of root to leaf binary numbers
1,022
0.737
Easy
16,734
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1164720/WEEB-DOES-PYTHON-BFS
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: queue, total = deque([(root, [root.val], 0)]), 0 while queue: curNode, curpath, length = queue.popleft() if not curNode.left and not curNode.right: for val in curpath: if val == 1: total += 2 ** length length -= 1 if curNode.left: queue.append((curNode.left, curpath + [curNode.left.val], length + 1)) if curNode.right: queue.append((curNode.right, curpath + [curNode.right.val], length + 1)) return total
sum-of-root-to-leaf-binary-numbers
WEEB DOES PYTHON BFS
Skywalker5423
2
115
sum of root to leaf binary numbers
1,022
0.737
Easy
16,735
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1930372/Python-Recursive-Solution-%2B-Bitwise-Logic
class Solution: def sumRootToLeaf(self, node, temp=0): res = 0 if node.left == node.right == None: return (temp<<1) + node.val if node.left: res += self.sumRootToLeaf(node.left, (temp<<1) + node.val) if node.right: res += self.sumRootToLeaf(node.right,(temp<<1) + node.val) return res
sum-of-root-to-leaf-binary-numbers
Python - Recursive Solution + Bitwise Logic
domthedeveloper
1
79
sum of root to leaf binary numbers
1,022
0.737
Easy
16,736
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1737259/Python-Simple
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode], res = "") -> int: if root is None: return 0 if root.left is None and root.right is None: return int( res+str(root.val) , 2) return self.sumRootToLeaf(root.left, res+str(root.val)) + self.sumRootToLeaf(root.right, res+str(root.val))
sum-of-root-to-leaf-binary-numbers
Python - Simple
lokeshsenthilkumar
1
114
sum of root to leaf binary numbers
1,022
0.737
Easy
16,737
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1737259/Python-Simple
class Solution: def sumNumbers(self, root: Optional[TreeNode], res = "") -> int: if root is None: return 0 if root.left is None and root.right is None: return int(res + str(root.val)) return self.sumNumbers(root.left, res+str(root.val)) + self.sumNumbers(root.right, res+str(root.val))
sum-of-root-to-leaf-binary-numbers
Python - Simple
lokeshsenthilkumar
1
114
sum of root to leaf binary numbers
1,022
0.737
Easy
16,738
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/759073/Python3-simplest-(28-ms)
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: if not root:return 0 ans=0 def dfs(node,bstr): nonlocal ans if not node.left and not node.right: ans += int(bstr,2) if node.left: left = dfs(node.left,bstr+str(node.left.val)) if node.right: right = dfs(node.right,bstr+str(node.right.val)) dfs(root,str(root.val)) return ans
sum-of-root-to-leaf-binary-numbers
Python3 simplest (28 ms)
harshitCode13
1
66
sum of root to leaf binary numbers
1,022
0.737
Easy
16,739
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/2794807/easy-python-solution-recursion
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: binaryList = [] self.helper(root,binaryList) return sum(int(x,2) for x in binaryList) def helper(self,root,binaryList,text = ""): if root: if root.left is None and root.right is None: binaryList.append(text+str(root.val)) print(binaryList) return self.helper(root.left,binaryList, text + str(root.val)) or self.helper(root.right, binaryList,text + str(root.val))
sum-of-root-to-leaf-binary-numbers
easy python solution recursion
betaal
0
3
sum of root to leaf binary numbers
1,022
0.737
Easy
16,740
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1910424/Python3-Simple-Solution-Faster-Than-87.08
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: sm, s = [], "" def dfs(tree, s): if tree.left is None and tree.right is None: s += str(tree.val) sm.append(int(s, 2)) s += str(tree.val) if tree.left: dfs(tree.left, s) if tree.right: dfs(tree.right, s) dfs(root, s) return sum(sm)
sum-of-root-to-leaf-binary-numbers
Python3 Simple Solution, Faster Than 87.08%
Hejita
0
37
sum of root to leaf binary numbers
1,022
0.737
Easy
16,741
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1695998/Python3-Faster-than-99
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: numbers = [] number = b"" self.helper(root, number, numbers) return sum(numbers) def helper(self, node, number, numbers): if node: number = number + b"1" if node.val else number + b"0" if not (node.left or node.right): numbers += [int(number, 2)] return self.helper(node.left, number, numbers) self.helper(node.right, number, numbers)
sum-of-root-to-leaf-binary-numbers
[Python3] Faster than 99%
agcoon
0
56
sum of root to leaf binary numbers
1,022
0.737
Easy
16,742
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1683809/Python3-BackTrack-or-Beginner-Friendly-or-Detailed-Commented
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: cand = [] # back_track def h1(cur=root, path=[]): if cur: path.append(str(cur.val)) print(cur.val) # print(path) if not (cur.left or cur.right): cand.append(''.join(path)) if cur.left: h1(cur.left, path) path.pop() if cur.right: h1(cur.right, path) path.pop() # add ans def h2(l): ans = 0 for x in l: ans += int(x, 2) return ans # back_track O(N) h1() return h2(cand)
sum-of-root-to-leaf-binary-numbers
Python3 BackTrack | Beginner Friendly | Detailed Commented
doneowth
0
19
sum of root to leaf binary numbers
1,022
0.737
Easy
16,743
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1682418/PYTHON3-oror-FAST-Solution
class Solution: def SumOf(self, root: Optional[TreeNode],num): if not root: return num = num*2 + root.val if not root.left and not root.right: self.Sum+=num self.SumOf(root.left, num) self.SumOf(root.right, num) def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: self.Sum=0;num=0 self.SumOf(root,num) return self.Sum ```
sum-of-root-to-leaf-binary-numbers
[⭐️PYTHON3 || FAST Solution ]
alchimie54
0
17
sum of root to leaf binary numbers
1,022
0.737
Easy
16,744
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1682359/Python-dfs-leftshift-operation
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: def dfs(root, cur_sum): if not root: return 0 cur_sum <<= 1 cur_sum += root.val if not root.left and not root.right: return cur_sum return dfs(root.left, cur_sum) + dfs(root.right, cur_sum) return dfs(root, 0)
sum-of-root-to-leaf-binary-numbers
Python, dfs, leftshift operation
pradeep288
0
31
sum of root to leaf binary numbers
1,022
0.737
Easy
16,745
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1682198/simple-solution-in-python-USE-dfsbuilt-in-convertor
s Solution: ''' TOPIC:sum all branches from root to leaf. convert binary to decimal STEP:dfs traverse tree dfs(root, "") dfs(root, str(s+root.val)),handle subtotal add to sum 1.create helper(root,s) 2.if leaf handle subtotal,total += int(str(s+root.val), 2) convert binary to decimal 3.else, do recursion helper(root.left/right, str(s+root.val)) ATT: 1.avoid use global variable res or closure method, can use res with size 1 to pass to helper. Remember! primitive variable changed in helper won't affect main method 2.convert binary to decimal use int(Number, 2) ''' def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: res = [0]*1 self.preorder(root, res, "") return res[0] def preorder(self, root, res, s): if not root: return elif not root.left and not root.right: res[0] = res[0] + int(s+str(root.val), 2) return self.preorder(root.left, res, s + str(root.val)) self.preorder(root.right, res, s + str(root.val))
sum-of-root-to-leaf-binary-numbers
simple solution in python USE dfs,built-in convertor
DolphinFight
0
10
sum of root to leaf binary numbers
1,022
0.737
Easy
16,746
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1681855/Python-Easy-to-Understand
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: def binsum(node, path=''): path = path + str(node.val) if node.left is None and node.right is None: return int(path, base=2) left = right =0 if node.left: left = binsum(node.left, path) if node.right: right = binsum(node.right, path) return left+right return binsum(root)
sum-of-root-to-leaf-binary-numbers
Python Easy to Understand
matthewlkey
0
40
sum of root to leaf binary numbers
1,022
0.737
Easy
16,747
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1672034/Python-Simple-recursive-DFS-explained
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode], parent='') -> int: self.total = 0 self.recurse(root) return self.total def recurse(self, root, parent=''): if not root: return 0 # recursively check the left and right # subtrees only to stop if its either a # a None or a leaf child (processed below) self.recurse(root.left, parent+str(root.val)) self.recurse(root.right, parent+str(root.val)) # if it's a leaf, add the binary representation # of the path from the root to this leaf to the # running total sum (self.total) that we'll ret if not root.left and not root.right: self.total += int((parent + str(root.val)), 2) return
sum-of-root-to-leaf-binary-numbers
[Python] Simple recursive DFS explained
buccatini
0
49
sum of root to leaf binary numbers
1,022
0.737
Easy
16,748
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1599242/Python3-or-98-or-DFS-or-Easy-to-Understand
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: self.full_sum = 0 if not root: return self.full_sum def helper(node, path): if node.left is None and node.right is None: self.full_sum += path if node.left: helper(node.left, path*2 + node.left.val) if node.right: helper(node.right, path*2 + node.right.val) helper(root, root.val) return(self.full_sum)
sum-of-root-to-leaf-binary-numbers
Python3 | 98% | DFS | Easy to Understand
galileo757
0
44
sum of root to leaf binary numbers
1,022
0.737
Easy
16,749
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1569095/Python-recursion-faster-than-98
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode], curSum=0) -> int: curSum = 2 * curSum + root.val if root.left is None and root.right is None: return curSum res = 0 if root.left: res += self.sumRootToLeaf(root.left, curSum) if root.right: res += self.sumRootToLeaf(root.right, curSum) return res
sum-of-root-to-leaf-binary-numbers
Python recursion faster than 98%
dereky4
0
86
sum of root to leaf binary numbers
1,022
0.737
Easy
16,750
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1428582/Python3-Recursive-dfs
class Solution: def __init__(self): self.res = 0 def traversal(self, node, cur_number): if node == None: return None cur_number = (cur_number << 1) | node.val if not node.left and not node.right: self.res += cur_number return None self.traversal(node.left, cur_number) self.traversal(node.right, cur_number) def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: self.traversal(root, 0) return self.res
sum-of-root-to-leaf-binary-numbers
[Python3] Recursive dfs
maosipov11
0
48
sum of root to leaf binary numbers
1,022
0.737
Easy
16,751
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1382525/Python3-faster-than-98.24
class Solution: s = 0 def sumRootToLeaf(self, root: TreeNode) -> int: def traverse(cur: TreeNode, sofar: str): if cur.left is None and cur.right is None: val = int(sofar + str(cur.val), 2) self.s += val return if cur.left is not None: traverse(cur.left, sofar + str(cur.val)) if cur.right is not None: traverse(cur.right, sofar + str(cur.val)) traverse(root, "") return self.s
sum-of-root-to-leaf-binary-numbers
Python3 - faster than 98.24%
CC_CheeseCake
0
32
sum of root to leaf binary numbers
1,022
0.737
Easy
16,752
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/836337/Sum-of-Root-To-Leaf-Binary-Numbers-Solutionor-Python-or-DFS-or-Comments-added
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: # calculate dfs of a tree l=[] return(self.dfs(root,l)) def dfs(self,root,l): if root is None: # if the tree is empty return 0 l.append(root.val) # keep adding the values encountered during traversal if root.left is None and root.right is None: s=self.change(l) # return the decimal equivalent if leaf-node found else: s=self.dfs(root.left,l)+self.dfs(root.right,l) #adds the sum returned from right and left subtree l.pop() #pop operation discards the node for which dfs is finished. return (s) def change(self,s): # binary to decimal conversion t=0 p=0 for i in range(len(s)-1,-1,-1): p+=s[i]*(2**t) t+=1 return p
sum-of-root-to-leaf-binary-numbers
Sum of Root To Leaf Binary Numbers Solution| Python | DFS | Comments added
shikha9433
0
32
sum of root to leaf binary numbers
1,022
0.737
Easy
16,753
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/477620/Easy-to-understand-Python-DFS-cleancode-Int()-function
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: self.res=0 def helper(root,string=''): if root.left: helper(root.left,string+str(root.val)) if root.right: helper(root.right,string+str(root.val)) if not root.left and not root.right: self.res += int(string+str(root.val),2) helper(root) return self.res
sum-of-root-to-leaf-binary-numbers
Easy to understand, Python, DFS, cleancode, Int() function
rahulreddyk2010
0
73
sum of root to leaf binary numbers
1,022
0.737
Easy
16,754
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/372034/DFS-Path-Storing-Recursion
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: binaryNumbers = self.pathFinder(root) s = 0 for num in binaryNumbers: s += int(num, 2) return s def pathFinder(self, root): if root is None: return [] if root.left is None and root.right is None: return [str(root.val)] lp = self.pathFinder(root.left) rp = self.pathFinder(root.right) left = [str(root.val) + str(p) for p in lp] right = [str(root.val) + str(p) for p in rp] return left + right
sum-of-root-to-leaf-binary-numbers
DFS Path Storing Recursion
uds5501
0
121
sum of root to leaf binary numbers
1,022
0.737
Easy
16,755
https://leetcode.com/problems/camelcase-matching/discuss/488216/Python-Two-Pointer-Memory-usage-less-than-100
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: def match(p, q): i = 0 for j, c in enumerate(q): if i < len(p) and p[i] == q[j]: i += 1 elif q[j].isupper(): return False return i == len(p) return [True if match(pattern, s) else False for s in queries]
camelcase-matching
Python - Two Pointer - Memory usage less than 100%
mmbhatk
8
638
camelcase matching
1,023
0.602
Medium
16,756
https://leetcode.com/problems/camelcase-matching/discuss/1464303/Python3-solution
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: res = [] for word in queries: i = j = 0 while i < len(word): if j < len(pattern) and word[i] == pattern[j]: i += 1 j += 1 elif word[i].isupper(): break else: i += 1 if i == len(word) and j == len(pattern): res.append(True) else: res.append(False) return res
camelcase-matching
Python3 solution
EklavyaJoshi
4
139
camelcase matching
1,023
0.602
Medium
16,757
https://leetcode.com/problems/camelcase-matching/discuss/1007925/Python3-matching
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: def fn(query): """Return True if query matches pattern.""" i = 0 for x in query: if i < len(pattern) and x == pattern[i]: i += 1 elif x.isupper(): return False return i == len(pattern) return [fn(query) for query in queries]
camelcase-matching
[Python3] matching
ye15
1
65
camelcase matching
1,023
0.602
Medium
16,758
https://leetcode.com/problems/camelcase-matching/discuss/2842445/Python-Easy-Solution-Faster-Than-97.4
class Solution: def match(self, query, pattern): pidx = 0 for i in range(len(query)): if query[i].isupper(): if query[i]==pattern[pidx]: pidx+=1 else: return False else: if query[i]==pattern[pidx]: pidx+=1 if pidx==len(pattern): for j in range(i+1, len(query)): if query[j].isupper(): return False return True def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: ans = [False for _ in range(len(queries))] for i in range(len(queries)): if self.match(queries[i], pattern): ans[i]=True return ans
camelcase-matching
Python Easy Solution Faster Than 97.4%
amy279
0
2
camelcase matching
1,023
0.602
Medium
16,759
https://leetcode.com/problems/camelcase-matching/discuss/2838999/Python3-easy-to-understand
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: P = len(pattern) res = [False]*len(queries) for i, query in enumerate(queries): p = q = 0 Q = len(query) while q < Q and p < P: if query[q] == pattern[p]: q, p = q + 1, p + 1 elif query[q].islower(): q = q + 1 else: break if (q == Q and p == P) or (query[q:].islower() and p == P): res[i] = True return res
camelcase-matching
Python3 - easy to understand
mediocre-coder
0
1
camelcase matching
1,023
0.602
Medium
16,760
https://leetcode.com/problems/camelcase-matching/discuss/2830944/Go-Rust-and-Python-solution
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: out = [] for query in queries: count = 0 flag = 0 ans = "" for j in range(len(query)): if count < len(pattern): if query[j] == pattern[count]: ans+=query[j] count +=1 elif query[j] == query[j].upper(): flag = 1 break elif query[j:] != query[j:].lower(): flag=1 break else: break if flag == 0 and ans == pattern: out.append(True) else: out.append(False) return out
camelcase-matching
Go Rust and Python solution
anshsharma17
0
2
camelcase matching
1,023
0.602
Medium
16,761
https://leetcode.com/problems/camelcase-matching/discuss/2795134/Python-Easy-to-Understand-Faster-than-92.23
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: results = [] for query in queries: pIndex = 0 qIndex = 0 matched = False flag = False while pIndex < len(pattern) and qIndex < len(query): pchar = pattern[pIndex] qchar = query[qIndex] if pchar == qchar: pIndex = pIndex + 1 qIndex = qIndex + 1 else: if qchar.isupper(): matched = False flag = True break qIndex = qIndex + 1 if not flag: if pIndex < len(pattern): matched = False elif qIndex < len(query): matched = True while qIndex < len(query): if query[qIndex].isupper(): matched = False break qIndex = qIndex + 1 elif pIndex >= len(pattern) and qIndex >= len(query): matched = True results.append(matched) return results
camelcase-matching
Python, Easy to Understand - Faster than 92.23%
jagadeeshraghu24
0
1
camelcase matching
1,023
0.602
Medium
16,762
https://leetcode.com/problems/camelcase-matching/discuss/2521265/Python3-solution-explained
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: ans, d = [], {} for i in range(len(pattern)): if pattern[i].isupper(): if pattern[i] not in d: d[pattern[i]] = 1 else: d[pattern[i]] += 1 for i in range(len(queries)): b, k, d1 = True, 0, d.copy() for j in range(len(queries[i])): if k < len(pattern) and queries[i][j] == pattern[k]: k += 1 if queries[i][j].isupper() and (queries[i][j] not in d1 or d1[queries[i][j]] == 0): b = False break elif queries[i][j].isupper() and queries[i][j] in d1: d1[queries[i][j]] -= 1 if k != len(pattern): b = False ans.append(b) return ans
camelcase-matching
Python3 solution explained
FlorinnC1
0
34
camelcase matching
1,023
0.602
Medium
16,763
https://leetcode.com/problems/camelcase-matching/discuss/2051550/Python-or-Two-Pointers-or-With-Explanation-or-Easy-to-Understand
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: return [True if self.compare(s, pattern) else False for s in queries] def compare(self, s, pattern): # two pointers, i for s, j for pattern # If s[i] matches pattern[j], increase pattern pointer # if does not match and s[i] is in lowercase, continue # if does not match and s[i] is in uppercase, return false n = len(pattern) j = 0 for i, char in enumerate(s): if j < n and s[i] == pattern[j]: j += 1 else: if s[i].islower(): continue elif s[i].isupper(): return False return j == n
camelcase-matching
Python | Two Pointers | With Explanation | Easy to Understand
Mikey98
0
124
camelcase matching
1,023
0.602
Medium
16,764
https://leetcode.com/problems/camelcase-matching/discuss/2010193/PYTHON-SOL-oror-SUBSEQUENCE-oror-SIMPLE-oror-EXPLAINED-oror
class Solution: def CountCapitals(self,string): ans = 0 for i in string: if 65 <= ord(i) <= 90: ans += 1 return ans def subsequence(self,str1,str2): n1,n2 = len(str1),len(str2) dp = [[0 for i in range(n2+1)] for j in range(n1+1)] for i in range(1,n1+1): for j in range(1,n2+1): if str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 else: dp[i][j] = dp[i-1][j] if dp[i-1][j] > dp[i][j-1] else dp[i][j-1] return dp[-1][-1] == n2 def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: capital_pattern = self.CountCapitals(pattern) ans = [] for query in queries: if self.CountCapitals(query) == capital_pattern: if self.subsequence(query,pattern): ans.append(True) else: ans.append(False) else: ans.append(False) return ans
camelcase-matching
PYTHON SOL || SUBSEQUENCE || SIMPLE || EXPLAINED ||
reaper_27
0
54
camelcase matching
1,023
0.602
Medium
16,765
https://leetcode.com/problems/camelcase-matching/discuss/980644/16ms-Find-Pattern-and-Check-Upper
class Solution: def camelMatch(self, queries, pattern): return [Solution.match(q, pattern) for q in queries] @staticmethod def match(query, pattern): hit = [] idx_start = 0 for p in pattern: idx_find = query.find(p, idx_start) if idx_find == -1: return False for letter in query[idx_start:idx_find]: if letter.isupper(): return False hit.append(idx_find) idx_start = idx_find + 1 for letter in query[idx_start:]: if letter.isupper(): return False return True
camelcase-matching
16ms, Find Pattern and Check Upper
steve-jokes
0
74
camelcase matching
1,023
0.602
Medium
16,766
https://leetcode.com/problems/video-stitching/discuss/2773366/greedy
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: end, end2, res = -1, 0, 0 for i, j in sorted(clips): if end2 >= T or i > end2: break elif end < i <= end2: res, end = res + 1, end2 end2 = max(end2, j) return res if end2 >= T else -1
video-stitching
greedy
yhu415
0
1
video stitching
1,024
0.505
Medium
16,767
https://leetcode.com/problems/video-stitching/discuss/2620056/Clear-greedy-python-solution
class Solution: def videoStitching(self, clips: List[List[int]], time: int) -> int: if (time == 0): return 0 clips.sort(key=lambda i: (i[0], -i[1])) output = [clips[0]] start, end = output[-1][0], output[-1][1] for currStart, currEnd in clips[1:]: if (currStart <= end <= currEnd and end < time): # pop the last clip if the second last clip overlaps with current clip and current clip is longer than the last clip if (len(output) > 1 and currStart <= output[-2][1]): output.pop() start = min(start, currStart) end = max(end, currEnd) output.append([currStart, currEnd]) if (start <= 0 and end >= time): return len(output) else: return -1
video-stitching
Clear greedy python solution
leqinancy
0
13
video stitching
1,024
0.505
Medium
16,768
https://leetcode.com/problems/video-stitching/discuss/2010409/PYTHON-SOL-oror-UNIQUE-SELF-MADE-oror-LONGEST-INC-SUBSEQUENCE-oror-VERY-EASY-oror-EXPLAINED
class Solution: def videoStitching(self, clips: List[List[int]], time: int) -> int: # first sort the clips clips.sort() # if start is not 0 we can never cover entire event if clips[0][0] != 0 : return -1 # dictionary (key,value) key = int value = max int we can reach from value in 1 move dictionary = {} for x,y in clips: dictionary[x] = y # make a dp list dp = [float('inf')]*(time+1) dp[0] = 0 for i in range(1,time+1): best = dp[i] for j in range(i): # can we reach i or above i from j if j in dictionary and dictionary[j] >= i: # if yes can we reach in minimum steps so far if dp[j] + 1 < best: best = dp[j] + 1 if best == float('inf'):return -1 dp[i] = best return dp[-1] if dp[-1] != float('inf') else -1
video-stitching
PYTHON SOL || UNIQUE SELF MADE || LONGEST INC SUBSEQUENCE || VERY EASY || EXPLAINED
reaper_27
0
53
video stitching
1,024
0.505
Medium
16,769
https://leetcode.com/problems/video-stitching/discuss/1511710/Python-100-Fast-Swipe-Line-or-DP
class Solution: def videoStitching(self, clips: List[List[int]], time: int) -> int: # Swipe Line clips.sort() if clips[0][0] != 0: return -1 intervals = [(clips[0][0], clips[0][1])] for c in clips[1:]: l, r = c if intervals[-1][1] < l: break if intervals[-1][1] < r: while intervals and intervals[-1][0] >= l: intervals.pop() if not intervals: intervals.append((l, r)) elif intervals[-1][1] < r: intervals.append((intervals[-1][1], r)) ret = 0 for intv in intervals: ret += 1 if time <= intv[-1]: return ret return -1 # DP clips.sort() dp = [0] + [sys.maxsize] * time clips = sorted(clips) for clip in clips: s, e = clip[0], clip[1] for j in range(s, min(e, time)): dp[j+1] = min(dp[j+1], dp[s] + 1) return -1 if dp[-1] == sys.maxsize else dp[-1]
video-stitching
Python 100% Fast Swipe Line or DP
BichengWang
0
135
video stitching
1,024
0.505
Medium
16,770
https://leetcode.com/problems/video-stitching/discuss/271143/python-DFS
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: from collections import defaultdict clip_map = defaultdict(list) clips.sort() for i, (s_i, e_i) in enumerate(clips): for s_j, e_j in clips[:i] + clips[i + 1:]: if s_i < s_j <= e_i and e_j > e_i: clip_map[(s_i, e_i)].append((s_j, e_j)) res = float('inf') for c in clips: q, path = [], 1 if c[0] != 0: continue if c[1] >= T: return 1 q = clip_map[tuple(c)] while q: s, e = q.pop() path += 1 if e >= T: break q += clip_map[(s, e)] else: path = float('inf') res = min(res, path) return -1 if res == float('inf') else res
video-stitching
python DFS
imiochen24
0
70
video stitching
1,024
0.505
Medium
16,771
https://leetcode.com/problems/video-stitching/discuss/1008139/Python3-greedy-O(NlogN)
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: if not T: return 0 # edge case ans = yy = mx = 0 for x, y in sorted(clips): if mx < x: return -1 # gap if yy < x <= mx: ans, yy = ans+1, mx mx = max(mx, y) if T <= mx: return ans + 1 return -1 # not reaching T
video-stitching
[Python3] greedy O(NlogN)
ye15
-1
75
video stitching
1,024
0.505
Medium
16,772
https://leetcode.com/problems/divisor-game/discuss/382233/Solution-in-Python-3-(With-Detailed-Proof)
class Solution: def divisorGame(self, N: int) -> bool: return N % 2 == 0 - Junaid Mansuri (LeetCode ID)@hotmail.com
divisor-game
Solution in Python 3 (With Detailed Proof)
junaidmansuri
150
6,100
divisor game
1,025
0.672
Easy
16,773
https://leetcode.com/problems/divisor-game/discuss/279544/python3-beats-100
class Solution: def divisorGame(self, N: int) -> bool: if N%2 ==1: return False else: return True
divisor-game
python3 beats 100%
Lilbud_314
4
544
divisor game
1,025
0.672
Easy
16,774
https://leetcode.com/problems/divisor-game/discuss/1463601/One-Line-Solution
class Solution: def divisorGame(self, n: int) -> bool: return n%2 ==0
divisor-game
One Line Solution
_r_rahul_
2
136
divisor game
1,025
0.672
Easy
16,775
https://leetcode.com/problems/divisor-game/discuss/1493414/Python-99.5-speed-faster
class Solution: def divisorGame(self, n: int) -> bool: return n%2 == 0
divisor-game
Python // 99.5% speed faster
fabioo29
1
432
divisor game
1,025
0.672
Easy
16,776
https://leetcode.com/problems/divisor-game/discuss/1119967/Python-3-one-line-solution
class Solution: def divisorGame(self, N: int) -> bool: return N%2==0
divisor-game
Python 3, one line solution
PracticeLeetCodes
1
245
divisor game
1,025
0.672
Easy
16,777
https://leetcode.com/problems/divisor-game/discuss/2741482/Java-C%2B%2B-Python
class Solution: def divisorGame(self, n: int) -> bool: return n%2 == 0;
divisor-game
Java / C++/ Python
rahulb_001
0
2
divisor game
1,025
0.672
Easy
16,778
https://leetcode.com/problems/divisor-game/discuss/2656315/Easy-python-DP-with-explanations.
class Solution: def divisorGame(self, n: int) -> bool: if n == 1: return False elif n == 2: return True res = [0] * (n+1) res[0] = 1 res[1] = 0 res[2] = 1 for i in range(3, n+1): choices = [j for j in range(1,n) if i%j == 0] if len(choices) == 1: break for c in choices: if i-c < 0: break if res[i-c] == 0: # if I can make others lose, then I win. res[i] = 1 break return res[-1]
divisor-game
Easy python DP with explanations.
xiangyupeng1994
0
9
divisor game
1,025
0.672
Easy
16,779
https://leetcode.com/problems/divisor-game/discuss/2547184/EASY-PYTHON3-SOLUTION
class Solution: def divisorGame(self, n: int) -> bool: return True if n%2==0 else False
divisor-game
🔥 EASY PYTHON3 SOLUTION 🔥
rajukommula
0
69
divisor game
1,025
0.672
Easy
16,780
https://leetcode.com/problems/divisor-game/discuss/2403744/Python3-or-Solved-Using-Bottom-Up-DP-%2B-Tabulation
class Solution: def divisorGame(self, n: int) -> bool: #here, the state will have single parameter: current number on chalkboard! #Depending on current number on chalkboard, the player to make the first move #can either win or lose! #I will take bottom-up approach and use a dp table filling it from the most #trivial base case of n=1 up to original n! #size n+1 for indices from 0 to n, where we don't use index 0! dp = [None] * (n+1) #player who plays when 1 on board loses! dp[1] = False #iterate through state's parameters in inc. order to fill our dp table! for i in range(2, n+1, 1): #iterate through each and every number btw 1 and i//2 #we know that any number greater than i//2 can never be a factor of i! can_win = False for a in range(1, (i//2) + 1, 1): if(i % a == 0): #if player playing at i-a number on board will lose, then #current player that played first when i was on board can win #since he will choose the most optimal path for him! if(dp[i - a] == False): can_win = True break #once we tried all possible numbers btw 0 and i that are factors of i, #we check boolean flag! if(can_win): dp[i] = True else: dp[i] = False #since dp[n] equals True if Alice starts first and can win or False otherewise! return dp[n]
divisor-game
Python3 | Solved Using Bottom-Up DP + Tabulation
JOON1234
0
59
divisor game
1,025
0.672
Easy
16,781
https://leetcode.com/problems/divisor-game/discuss/2397679/Python-Dynamic-Programming-Solution
class Solution: def divisorGame(self, n: int) -> bool: store = [False for i in range(n+1)] for i in range(2,n+1): divisor = i // 2 while divisor > 0: if i % divisor == 0 and store[i - divisor] == False: store[i] = True break divisor = divisor - 1 return store[-1]
divisor-game
Python Dynamic Programming Solution
headoftheport1230
0
59
divisor game
1,025
0.672
Easy
16,782
https://leetcode.com/problems/divisor-game/discuss/2279656/Python-Solution
class Solution: def divisorGame(self, n: int) -> bool: for i in range(n): if(n%2==0): return True return False
divisor-game
Python Solution
yashkumarjha
0
129
divisor game
1,025
0.672
Easy
16,783
https://leetcode.com/problems/divisor-game/discuss/2270082/Divisor-Game-or-Python3(Bottom-Up-Memoization-Approach)
class Solution: def divisorGame(self, n: int) -> bool: arr = [None, False] if n == 1: return arr[n] #running this for loop n-1 times for i in range(2, n+1): one_less = i - 1 if(arr[one_less] == False): arr.append(True) else: arr.append(False) return arr[n]
divisor-game
Divisor Game | Python3(Bottom-Up Memoization Approach)
JOON1234
0
46
divisor game
1,025
0.672
Easy
16,784
https://leetcode.com/problems/divisor-game/discuss/1916640/Python-One-Line-Math-Solution-Faster-Than-95.52
class Solution: def divisorGame(self, n: int) -> bool: return True if n % 2 == 0 else False
divisor-game
Python One Line Math Solution Faster Than 95.52%
Hejita
0
162
divisor game
1,025
0.672
Easy
16,785
https://leetcode.com/problems/divisor-game/discuss/1850015/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-70
class Solution: def divisorGame(self, n: int) -> bool: return n%2==0
divisor-game
1-Line Python Solution || 90% Faster || Memory less than 70%
Taha-C
0
98
divisor game
1,025
0.672
Easy
16,786
https://leetcode.com/problems/divisor-game/discuss/1817927/Python-Solution
class Solution: def divisorGame(self, n: int) -> bool: alice = False while n > 1: x = 0 for i in range(1,n//2+1): if n % i == 0: x = i break n -= x alice = not alice return alice
divisor-game
Python Solution
MS1301
0
99
divisor game
1,025
0.672
Easy
16,787
https://leetcode.com/problems/divisor-game/discuss/1056614/Memory-Usage-less-than-90.60-of-Python3-online-submissions
class Solution: def divisorGame(self, N: int) -> bool: #N = 3 count = 0 while N>1: N = self.divide(N) count +=1 return count%2!=0 def divide(self,N): for i in range(1,N): if N%i== 0: return N-i
divisor-game
Memory Usage less than 90.60% of Python3 online submissions
xevb
0
114
divisor game
1,025
0.672
Easy
16,788
https://leetcode.com/problems/divisor-game/discuss/1051696/Python3-simple-solution-%22one-liner%22
class Solution: def divisorGame(self, N: int) -> bool: return N % 2 == 0
divisor-game
Python3 simple solution "one-liner"
EklavyaJoshi
0
169
divisor game
1,025
0.672
Easy
16,789
https://leetcode.com/problems/divisor-game/discuss/275027/Python3-Minimax-with-memoization-68ms-beats-100-atm
class Solution: winnums = [] losenums = [1] def divisorGame(self, N: int) -> bool: if self.calcGame(N) >=0 : return True else: return False def calcGame(self, N): divisors = [] if N in self.winnums: return 1 if N in self.losenums: return -1 for num in range(1,N): if N % num == 0: divisors.append(num) if len(divisors)==0: self.losenums.append(N) return -1 for divisor in divisors: newNum = N-divisor profit = - self.calcGame(newNum) if profit == 0: continue if profit >= 0: self.winnums.append(N) return 1 self.losenums.append(N) return -1
divisor-game
[Python3] Minimax with memoization 68ms beats 100% atm
vlais
0
182
divisor game
1,025
0.672
Easy
16,790
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1657537/Python3-Simplifying-Tree-to-Arrays-oror-Detailed-Explanation-%2B-Intuition-oror-Preorder-DFS
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: def dfs(root, mn, mx): # Base Case: If we reach None, just return 0 in order not to affect the result if not root: return 0 # The best difference we can do using the current node can be found: res = max(abs(root.val - mn), abs(root.val - mx)) # Recompute the new minimum and maximum taking into account the current node mn, mx = min(mn, root.val), max(mx, root.val) # Recurse left and right using the newly computated minimum and maximum return max(res, dfs(root.left, mn, mx), dfs(root.right, mn, mx)) # Initialize minimum `mn` and maximum `mx` equals value of given root return dfs(root, root.val, root.val)
maximum-difference-between-node-and-ancestor
✅ [Python3] Simplifying Tree to Arrays || Detailed Explanation + Intuition || Preorder DFS
PatrickOweijane
10
509
maximum difference between node and ancestor
1,026
0.734
Medium
16,791
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/930417/Python-DFS-solution-O(N)-space-and-time
class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: self.maxx = 0 self.dfs(root) return self.maxx def dfs(self, root): if not root.left and not root.right: return root.val, root.val if not root.left: l_min, l_max = root.val, root.val else: l_min, l_max = self.dfs(root.left) if not root.right: r_min, r_max = root.val, root.val else: r_min, r_max = self.dfs(root.right) self.maxx=max(self.maxx,abs(root.val-l_min),abs(root.val-l_max),abs(root.val-r_min),abs(root.val-r_max)) return min(root.val,l_min,r_min), max(root.val,l_max,r_max)
maximum-difference-between-node-and-ancestor
[Python] DFS solution - O(N) space and time
realslimshady
2
130
maximum difference between node and ancestor
1,026
0.734
Medium
16,792
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1775856/python3-short-dfs-solution
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: self.ans=0 def dfs(root,mn,mx): if root==None: self.ans=max(self.ans,abs(mx-mn)) return dfs(root.left,min(mn,root.val),max(mx,root.val)) dfs(root.right,min(mn,root.val),max(mx,root.val)) dfs(root,root.val,root.val) return self.ans
maximum-difference-between-node-and-ancestor
python3 short dfs solution
Karna61814
1
28
maximum difference between node and ancestor
1,026
0.734
Medium
16,793
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1674603/Python3-solution
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: ans = 0 stack = [[root, root.val, root.val]] while stack: node, a, b = stack.pop() if node.left: stack.append([node.left, max(node.left.val, a), min(node.left.val, b)]) ans = max(ans, stack[-1][1] - stack[-1][2]) if node.right: stack.append([node.right, max(node.right.val, a), min(node.right.val, b)]) ans = max(ans, stack[-1][1] - stack[-1][2]) return ans
maximum-difference-between-node-and-ancestor
Python3 solution
EklavyaJoshi
1
24
maximum difference between node and ancestor
1,026
0.734
Medium
16,794
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1657411/Clean-recursive-solution-in-Python-beats-94.83-(29ms)
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: def rec(root, min_so_far, max_so_far): if not root: return nonlocal res min_so_far, max_so_far = min(min_so_far, root.val), max(max_so_far, root.val) res = max(res, root.val - min_so_far, max_so_far - root.val) rec(root.left, min_so_far, max_so_far); rec(root.right, min_so_far, max_so_far); res = 0 rec(root, math.inf, -math.inf) return res
maximum-difference-between-node-and-ancestor
Clean recursive solution in Python, beats 94.83% (29ms)
kryuki
1
88
maximum difference between node and ancestor
1,026
0.734
Medium
16,795
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/2069756/Python-solution
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: def dfs(root, maxval, minval): if root is None: return 0 if root.val > maxval: maxval = root.val if root.val < minval: minval = root.val left = dfs(root.left, maxval, minval) right = dfs(root.right, maxval, minval) return max(left, right, abs(maxval - minval)) if not root: return 0 return dfs(root, root.val, root.val)
maximum-difference-between-node-and-ancestor
Python solution
user6397p
0
24
maximum difference between node and ancestor
1,026
0.734
Medium
16,796
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/2034465/Python-Solution
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: def helper(node,minVal, maxVal, diff): if node is None: return float('inf'), float('-inf'),diff minVal1, maxVal1, diff = helper(node.left,float('inf'), float('-inf'),diff) minVal2, maxVal2, diff = helper(node.right,float('inf'), float('-inf'),diff) minVal = min(minVal1, minVal2, node.val) maxVal = max(maxVal1, maxVal2, node.val) diff = max(diff, abs(minVal-node.val), abs(maxVal-node.val)) return minVal,maxVal,diff _,_,maxDiff = helper(root,float('inf'), float('-inf'),0) return maxDiff ``
maximum-difference-between-node-and-ancestor
Python Solution
b160106
0
26
maximum difference between node and ancestor
1,026
0.734
Medium
16,797
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1858462/python-easy-recursive-solution
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: res = float('-inf') def dfs(node): # return min, max under node nonlocal res if not node: return # node exists t = node.val minv = t maxv = t if node.left: left_min, left_max = dfs(node.left) res = max(res, abs(t-left_min), abs(t-left_max)) minv = min(minv, left_min) maxv = max(maxv, left_max) if node.right: right_min, right_max = dfs(node.right) res = max(res, abs(t-right_min), abs(t-right_max)) minv = min(minv, right_min) maxv = max(maxv, right_max) return minv, maxv dfs(root) return res
maximum-difference-between-node-and-ancestor
python easy recursive solution
byuns9334
0
30
maximum difference between node and ancestor
1,026
0.734
Medium
16,798
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1657632/Python3-RECURSION-(-)-Explained
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: self.diff = -1 def rec(root): if not root: return set() max_min = rec(root.left).union(rec(root.right)) for val in max_min: self.diff = max(self.diff, abs(root.val - val)) max_min.add(root.val) return {min(max_min), max(max_min)} rec(root) return self.diff
maximum-difference-between-node-and-ancestor
✔️ [Python3] RECURSION ( ͡👁️ ͜ʖ ͡👁️)✌, Explained
artod
0
33
maximum difference between node and ancestor
1,026
0.734
Medium
16,799