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/invert-binary-tree/discuss/1715762/Simple-Recursive-Python-Solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: # base condition if root is None: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left , root.right = right, left return root
invert-binary-tree
Simple Recursive Python Solution
dos_77
1
97
invert binary tree
226
0.734
Easy
4,100
https://leetcode.com/problems/invert-binary-tree/discuss/1653799/Python-Simple-iterative-BFS
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return root # setup our queue queue = collections.deque([root]) while queue: node = queue.popleft() if node: # if there's either of the children # present, swap them (works for even # if one is null and the other is not if node.left or node.right: node.left, node.right = node.right, node.left # we're going to append the children # of the current node even if they are # null since we're doing a check # while popping from the queue queue.append(node.left) queue.append(node.right) return root
invert-binary-tree
[Python] Simple iterative BFS
buccatini
1
69
invert binary tree
226
0.734
Easy
4,101
https://leetcode.com/problems/invert-binary-tree/discuss/1578090/Easy-solution-python
class Solution: def fun(self,root): if root is None: return root.left,root.right = root.right,root.left self.fun(root.left) self.fun(root.right) def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: self.fun(root) return root
invert-binary-tree
Easy solution python
Brillianttyagi
1
212
invert binary tree
226
0.734
Easy
4,102
https://leetcode.com/problems/invert-binary-tree/discuss/1540788/Python3-solutions
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return root root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
invert-binary-tree
Python3 solutions
dalechoi
1
138
invert binary tree
226
0.734
Easy
4,103
https://leetcode.com/problems/invert-binary-tree/discuss/1540788/Python3-solutions
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root def invertNode(node): node.left, node.right = node.right, node.left if node.left: invertNode(node.left) if node.right: invertNode(node.right) invertNode(root) return root
invert-binary-tree
Python3 solutions
dalechoi
1
138
invert binary tree
226
0.734
Easy
4,104
https://leetcode.com/problems/invert-binary-tree/discuss/1426087/Python-oror-Simple-Recursive-Solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def mirror(root): if root is None: return mirror(root.left) mirror(root.right) root.left, root.right = root.right, root.left mirror(root) return root
invert-binary-tree
Python || Simple Recursive Solution
naveenrathore
1
78
invert binary tree
226
0.734
Easy
4,105
https://leetcode.com/problems/invert-binary-tree/discuss/664986/Pythno3-3-line-recursive
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
invert-binary-tree
[Pythno3] 3-line recursive
ye15
1
39
invert binary tree
226
0.734
Easy
4,106
https://leetcode.com/problems/invert-binary-tree/discuss/664986/Pythno3-3-line-recursive
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: def fn(node): """Return root of tree that is inverted""" if not node: return node.left, node.right = fn(node.right), fn(node.left) return node return fn(root)
invert-binary-tree
[Pythno3] 3-line recursive
ye15
1
39
invert binary tree
226
0.734
Easy
4,107
https://leetcode.com/problems/invert-binary-tree/discuss/664986/Pythno3-3-line-recursive
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: stack = [root] while stack: node = stack.pop() if node: node.left, node.right = node.right, node.left stack.append(node.right) stack.append(node.left) return root
invert-binary-tree
[Pythno3] 3-line recursive
ye15
1
39
invert binary tree
226
0.734
Easy
4,108
https://leetcode.com/problems/invert-binary-tree/discuss/636182/Iterative-Python
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return None q = collections.deque() q.append(root) while q: node = q.popleft() if node.right: q.append(node.right) if node.left: q.append(node.left) node.left,node.right = node.right,node.left return root
invert-binary-tree
Iterative Python
pratushah
1
220
invert binary tree
226
0.734
Easy
4,109
https://leetcode.com/problems/invert-binary-tree/discuss/382635/Python-solutions
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return worklist = [root] while worklist: node = worklist.pop() node.left, node.right = node.right, node.left if node.right: worklist.append(node.right) if node.left: worklist.append(node.left) return root
invert-binary-tree
Python solutions
amchoukir
1
408
invert binary tree
226
0.734
Easy
4,110
https://leetcode.com/problems/invert-binary-tree/discuss/382635/Python-solutions
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root tmp = root.left root.left = self.invertTree(root.right) root.right = self.invertTree(tmp) return root
invert-binary-tree
Python solutions
amchoukir
1
408
invert binary tree
226
0.734
Easy
4,111
https://leetcode.com/problems/invert-binary-tree/discuss/2834865/python-beats-96.46
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return if root.left: self.invertTree(root.left) if root.right: self.invertTree(root.right) root.left, root.right = root.right, root.left return root
invert-binary-tree
[python] - beats 96.46%
ceolantir
0
3
invert binary tree
226
0.734
Easy
4,112
https://leetcode.com/problems/invert-binary-tree/discuss/2818030/Three-python-solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if(not root): return root q = [root] while(len(q) > 0): curr = q.pop(0) curr.right, curr.left = curr.left, curr.right if(curr.right): q.append(curr.right) if(curr.left): q.append(curr.left) return root
invert-binary-tree
Three python solution
jiad
0
2
invert binary tree
226
0.734
Easy
4,113
https://leetcode.com/problems/invert-binary-tree/discuss/2818030/Three-python-solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if(not root): return root root.right, root.left = root.left, root.right self.invertTree(root.left) self.invertTree(root.right) return root
invert-binary-tree
Three python solution
jiad
0
2
invert binary tree
226
0.734
Easy
4,114
https://leetcode.com/problems/invert-binary-tree/discuss/2818030/Three-python-solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if(not root): return root return TreeNode(root.val, self.invertTree(root.right), self.invertTree(root.left))
invert-binary-tree
Three python solution
jiad
0
2
invert binary tree
226
0.734
Easy
4,115
https://leetcode.com/problems/invert-binary-tree/discuss/2692337/Python-solution-faster-than-97
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: p = TreeNode() if root: p.val=root.val else: p=None def level(root,p): if not root: return if root.left: p.right = TreeNode() p.right.val = root.left.val level(root.left,p.right) if root.right: p.left = TreeNode() p.left.val = root.right.val level(root.right,p.left) level(root,p) return p
invert-binary-tree
Python solution faster than 97%
parthdixit
0
5
invert binary tree
226
0.734
Easy
4,116
https://leetcode.com/problems/invert-binary-tree/discuss/2690370/Invert-Binary-Tree
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root
invert-binary-tree
Invert Binary Tree
Erika_v
0
3
invert binary tree
226
0.734
Easy
4,117
https://leetcode.com/problems/invert-binary-tree/discuss/2690257/Easy-oror-Fast-oror-Recursion-oror-Python
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: return TreeNode(root.val, self.invertTree(root.right), self.invertTree(root.left))
invert-binary-tree
Easy || Fast || Recursion || Python
a3amaT
0
2
invert binary tree
226
0.734
Easy
4,118
https://leetcode.com/problems/invert-binary-tree/discuss/2686908/python-or-two-solutions-or-simple
class Solution: # recursive in divide and conquer def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def traverse(root): if not root: return # the only thing root to do is exchanging its left node and right node root.left, root.right = root.right, root.left # traverse left tree and right tree traverse(root.left) traverse(root.right) traverse(root) return root
invert-binary-tree
python | two solutions | simple
MichelleZou
0
25
invert binary tree
226
0.734
Easy
4,119
https://leetcode.com/problems/invert-binary-tree/discuss/2686908/python-or-two-solutions-or-simple
class Solution: # recursive in divide and conqueror def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None # inverse substree left = self.invertTree(root.left) right = self.invertTree(root.right) # inverse subnode root.left, root.right = right, left return root
invert-binary-tree
python | two solutions | simple
MichelleZou
0
25
invert binary tree
226
0.734
Easy
4,120
https://leetcode.com/problems/invert-binary-tree/discuss/2680412/python3-Sol.-Faster-then-96.63-only-9-line-ans
class Solution: def helper(self,root): if root is None: return root.left,root.right=root.right,root.left self.helper(root.left) self.helper(root.right) return root def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: return self.helper(root)
invert-binary-tree
python3 Sol. Faster then 96.63% only 9 line ans
pranjalmishra334
0
25
invert binary tree
226
0.734
Easy
4,121
https://leetcode.com/problems/invert-binary-tree/discuss/2546205/DFS-recursive-python-solution
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None temp = root.left root.left = root.right root.right = temp self.invertTree(root.left) self.invertTree(root.right) return root
invert-binary-tree
DFS recursive python solution
khushie45
0
53
invert binary tree
226
0.734
Easy
4,122
https://leetcode.com/problems/basic-calculator-ii/discuss/1209116/python-without-any-stack-and-beat-99
class Solution: def calculate(self, s: str) -> int: curr_res = 0 res = 0 num = 0 op = "+" # keep the last operator we have seen # append a "+" sign at the end because we can catch the very last item for ch in s + "+": if ch.isdigit(): num = 10 * num + int(ch) # if we have a symbol, we would start to calculate the previous part. # note that we have to catch the last chracter since there will no sign afterwards to trigger calculation if ch in ("+", "-", "*", "/"): if op == "+": curr_res += num elif op == "-": curr_res -= num elif op == "*": curr_res *= num elif op == "/": # in python if there is a negative number, we should alway use int() instead of // curr_res = int(curr_res / num) # if the chracter is "+" or "-", we do not need to worry about # the priority so that we can add the curr_res to the eventual res if ch in ("+", "-"): res += curr_res curr_res = 0 op = ch num = 0 return res
basic-calculator-ii
python - without any stack and beat 99%
ZAbird
14
1,300
basic calculator ii
227
0.423
Medium
4,123
https://leetcode.com/problems/basic-calculator-ii/discuss/1492325/Python-clean-stack-solution-(easy-understanding)
class Solution: def calculate(self, s: str) -> int: num, ope, stack = 0, '+', [] for cnt, i in enumerate(s): if i.isnumeric(): num = num * 10 + int(i) if i in '+-*/' or cnt == len(s) - 1: if ope == '+': stack.append(num) elif ope == '-': stack.append(-num) elif ope == '*': j = stack.pop() * num stack.append(j) elif ope == '/': j = int(stack.pop() / num) stack.append(j) ope = i num = 0 return sum(stack)
basic-calculator-ii
Python clean stack solution (easy understanding)
qaz6209031
9
1,400
basic calculator ii
227
0.423
Medium
4,124
https://leetcode.com/problems/basic-calculator-ii/discuss/1646913/Python3-GENERATOR-O(1)-Space-**-Explained
class Solution: def calculate(self, s: str) -> int: def get_term(): terminate = {'+', '-', '|'} term, sign = None, None cur = '' for ch in s + '|': if ch == ' ': continue if ch.isdigit(): cur += ch continue if sign: if sign == '*': term *= int(cur) else: term //= int(cur) else: term = int(cur) sign = ch if ch in terminate: yield (term, ch) term, sign = None, None cur = '' res = 0 prevSign = None for term, sign in get_term(): if not prevSign or prevSign == '+': res += term else: res -= term prevSign = sign return res
basic-calculator-ii
✔️ [Python3] GENERATOR, O(1) Space ฅ^•ﻌ•^ฅ, , Explained
artod
4
210
basic calculator ii
227
0.423
Medium
4,125
https://leetcode.com/problems/basic-calculator-ii/discuss/955621/Python3%3A-Solution-Using-Stack
class Solution: def calculate(self, s: str) -> int: stack = [] current_num = 0 operator = "+" operators = {"+", "-", "*", "/"} nums = set(str(x) for x in range(10)) for index, char in enumerate(s): if char in nums: current_num = current_num * 10 + int(char) if char in operators or index == len(s) - 1: if operator == "+": stack.append(current_num) elif operator == "-": stack.append(-current_num) elif operator == "*": stack[-1] = int(stack[-1] * current_num) else: stack[-1] = int(stack[-1] / current_num) current_num = 0 operator = char return sum(stack)
basic-calculator-ii
Python3: Solution Using Stack
MakeTeaNotWar
4
766
basic calculator ii
227
0.423
Medium
4,126
https://leetcode.com/problems/basic-calculator-ii/discuss/2670399/Python3%3A-O(1)-space-complexity-approach-(no-stack)
class Solution: def calculate(self, s: str) -> int: # Edge cases if len(s) == 0: # empty string return 0 # remove all spaces s = s.replace(" ", "") # Initialization curr_number = prev_number = result = 0 operation = "+" # intitialize the current operation to be "addition" i = 0 # initialize i while i < len(s): # len(s) is the length of the string char = s[i] # parsing ghe current currecter # if the character is digit if char.isdigit(): # current character is digit while i < len(s) and s[i].isdigit(): curr_number = curr_number * 10 + int(s[i]) # forming the number (112 for example) i += 1 # increment i by 1 if s[i] is still a digit i -= 1 # decrement i by 1 to go back to the location immediately before the current operation if operation == "+": result += curr_number # add the curr_number to the result prev_number = curr_number # update the previous number elif operation == "-": result -= curr_number # subtract the curr_number from the result prev_number = -curr_number # update the previous number elif operation == "*": result -= prev_number # subtract the previous number first result += prev_number * curr_number # add the result of multiplication prev_number = prev_number * curr_number # update the previous number elif operation == "/": result -= prev_number # subtract the previous number first result += int(prev_number/curr_number) # add the result of division prev_number = int(prev_number/curr_number) # update the previous number curr_number = 0 # reset the current number # if the character is an operation else: operation = char i += 1 # increment i by 1 return result
basic-calculator-ii
Python3: O(1) space-complexity approach (no stack)
ramyh
2
117
basic calculator ii
227
0.423
Medium
4,127
https://leetcode.com/problems/basic-calculator-ii/discuss/1926463/Python-easy-to-read-and-understand-or-stack
class Solution: def update(self, sign, num, stack): if sign == "+": stack.append(num) if sign == "-": stack.append(-num) if sign == "*": stack.append(stack.pop()*num) if sign == "/": stack.append(int(stack.pop()/num)) return stack def solve(self, i, s): stack, num, sign = [], 0, "+" while i < len(s): if s[i].isdigit(): num = num*10 + int(s[i]) elif s[i] in ["+", "-", "*", "/"]: stack = self.update(sign, num, stack) num, sign = 0, s[i] elif s[i] == "(": num, i = self.solve(i+1, s) elif s[i] == ")": stack = self.update(sign, num, stack) return sum(stack), i i += 1 #print(num, sign) stack = self.update(sign, num, stack) return sum(stack) def calculate(self, s: str) -> int: return self.solve(0, s)
basic-calculator-ii
Python easy to read and understand | stack
sanial2001
2
400
basic calculator ii
227
0.423
Medium
4,128
https://leetcode.com/problems/basic-calculator-ii/discuss/1721657/Python-stack-solution
class Solution: def calculate(self, s: str) -> int: stack = [] curr = 0 op = "+" if not s: return 0 operators = ['+','-','*',"/"] nums = set(str(x) for x in range(10)) for i in range(0,len(s)): # print(stack) ch = s[i] if ch in nums: curr = curr*10+int(ch) if ch in operators or i == len(s)-1: # print(op) if op == '+': stack.append(curr) elif op == '-': stack.append(-curr) elif op == '/': stack[-1] = int(stack[-1]/curr) elif op =="*": stack[-1] *= curr curr = 0 op = ch return sum(stack)
basic-calculator-ii
Python stack solution
Brillianttyagi
2
504
basic calculator ii
227
0.423
Medium
4,129
https://leetcode.com/problems/basic-calculator-ii/discuss/1915055/Python-or-Stack
class Solution: def calculate(self, s: str) -> int: stack = [] curr_op = "+" curr_num = "" s += " " for i in range(len(s)): if s[i] in "0123456789": curr_num += s[i] if s[i] in ["+","/","*","-"] or i == len(s)-1: if curr_op == "*": stack[-1] = stack[-1] * int(curr_num) elif curr_op == "/": stack[-1] = int(stack[-1] / int(curr_num)) elif curr_op == "+": stack.append(int(curr_num)) elif curr_op == "-": stack.append(int(curr_num)*-1) curr_num = "" curr_op = s[i] return sum(stack)
basic-calculator-ii
Python | Stack
iamskd03
1
150
basic calculator ii
227
0.423
Medium
4,130
https://leetcode.com/problems/basic-calculator-ii/discuss/1645594/Python3-O(n)-greater-O(1)-by-Only-Changing-2-Lines!-or-Stack-greater-Deque
class Solution: def calculate(self, s: str) -> int: nums = [] lastOp = None curNum = 0 for ch in s: if ch == ' ': continue if ch.isdigit(): curNum = curNum * 10 + int(ch) continue if not lastOp or lastOp == '+': nums.append(curNum) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;elif lastOp == '-': &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;nums.append(-curNum) elif lastOp == '*': nums.append(nums.pop() * curNum) elif lastOp == '/': nums.append(int(nums.pop() / curNum)) curNum = 0 lastOp = ch # Identical code performed on the last number we encounter if not lastOp or lastOp == '+': nums.append(curNum) elif lastOp == '-': nums.append(-curNum) elif lastOp == '*': nums.append(nums.pop() * curNum) elif lastOp == '/': nums.append(int(nums.pop() / curNum)) return sum(nums)
basic-calculator-ii
[Python3] O(n) -> O(1) by Only Changing 2 Lines! | Stack -> Deque
PatrickOweijane
1
688
basic calculator ii
227
0.423
Medium
4,131
https://leetcode.com/problems/basic-calculator-ii/discuss/1645594/Python3-O(n)-greater-O(1)-by-Only-Changing-2-Lines!-or-Stack-greater-Deque
class Solution: def calculate(self, s: str) -> int: nums = deque() lastOp = None curNum = 0 for ch in s: if ch == ' ': continue if ch.isdigit(): curNum = curNum * 10 + int(ch) continue if not lastOp or lastOp == '+': nums.append(curNum) elif lastOp == '-': nums.append(-curNum) elif lastOp == '*': nums.append(nums.pop() * curNum) elif lastOp == '/': nums.append(int(nums.pop() / curNum)) curNum = 0 lastOp = ch # Since we only need access to the last number in the stack, we can compute # the sum of the first two numbers and keep the third (last) number untouched. if len(nums) == 3: nums.appendleft(nums.popleft() + nums.popleft()) # Identical code performed on the last number we encounter if not lastOp or lastOp == '+': nums.append(curNum) elif lastOp == '-': nums.append(-curNum) elif lastOp == '*': nums.append(nums.pop() * curNum) elif lastOp == '/': nums.append(int(nums.pop() / curNum)) return sum(nums)
basic-calculator-ii
[Python3] O(n) -> O(1) by Only Changing 2 Lines! | Stack -> Deque
PatrickOweijane
1
688
basic calculator ii
227
0.423
Medium
4,132
https://leetcode.com/problems/basic-calculator-ii/discuss/1595383/Python-Easy-Solution-or-Handle-Negative-Division-Issue
class Solution: def calculate(self, s: str) -> int: sign = "+" stack = [] i = 0 res = 0 n = len(s) while i < n: ch = s[i] if ch.isdigit(): cur_val = 0 while i < n and s[i].isdigit(): cur_val = cur_val*10+int(s[i]) i += 1 i -= 1 if sign == "+": stack.append(cur_val) elif sign == "-": stack.append(-cur_val) elif sign == "*": val = stack.pop() stack.append(val*cur_val) elif sign == "/": val = stack.pop() stack.append(int(val/cur_val)) elif ch != " ": sign = ch i += 1 while len(stack) > 0: res += stack.pop() return res
basic-calculator-ii
Python Easy Solution | Handle Negative Division Issue ✔
leet_satyam
1
289
basic calculator ii
227
0.423
Medium
4,133
https://leetcode.com/problems/basic-calculator-ii/discuss/2840475/Python3-greater-Stack-Approach-Easy-to-understand.
class Solution: def calculate(self, s: str) -> int: s = s.replace(' ', '') stack, num, op = [], 0, '+' operations = '+-*/' for i in range(len(s)): if s[i].isdigit(): num = num * 10 + int(s[i]) if s[i] in operations or i == len(s) - 1: if op == '-': stack.append(-num) elif op == '+': stack.append(num) elif op == '*': stack.append(stack.pop() * num) else: stack.append(int(stack.pop() / num)) num = 0 op = s[i] return sum(stack)
basic-calculator-ii
✔️Python3 --> Stack Approach, Easy to understand.
radojicic23
0
1
basic calculator ii
227
0.423
Medium
4,134
https://leetcode.com/problems/basic-calculator-ii/discuss/2833921/python
class Solution: def calculate(self, s: str) -> int: i = 0 cur=prev=res =0 cur_operation ='+' while i <len(s): cur_char = s[i] if cur_char.isdigit(): while i < len(s) and s[i].isdigit(): cur = cur *10 + int(s[i]) i+=1 i-=1 if cur_operation=='+': res+=cur prev = cur elif cur_operation =='-': res -=cur prev = -cur elif cur_operation == '*': res -= prev res += prev*cur prev = prev*cur else: res -=prev res += int(prev/cur) prev = int(prev/cur) cur = 0 elif cur_char !=' ': cur_operation = cur_char i+=1 return res
basic-calculator-ii
python
Sangeeth_psk
0
2
basic calculator ii
227
0.423
Medium
4,135
https://leetcode.com/problems/basic-calculator-ii/discuss/2770785/Python3-Straightforward-Stack
class Solution: def calculate(self, s: str) -> int: stack, num, i, sign = [], 0, 0, '+' cur_op = None while i < len(s): # skip empty spaces if s[i] == ' ': i += 1 continue # extract number while i < len(s) and s[i].isdigit(): num = num*10 + int(s[i]) i += 1 # multiply or divide if that was the last operation if cur_op is not None: prev = stack.pop() num = abs(int(prev*num if cur_op == '*' else prev/num)) cur_op = None if i < len(s): # add to stack if s[i] in '+-': stack.append(num if sign == '+' else -num) num, sign = 0, s[i] # set as current operation elif s[i] in '*/': stack.append(num if sign == '+' else -num) num, cur_op = 0, s[i] i += 1 stack.append(num if sign == '+' else -num) # remaining number return sum(stack)
basic-calculator-ii
[Python3] Straightforward Stack
jonathanbrophy47
0
7
basic calculator ii
227
0.423
Medium
4,136
https://leetcode.com/problems/basic-calculator-ii/discuss/2665503/90-fasterororSimpleoror-O(1)-Space-O(N)-ComputionororPython
class Solution: def calculate(self, s: str) -> int: s=s.replace(' ','') last_num=0 curr_num=0 operand="+" net=0 for ch in s+'+': if ch==" ": continue if ch.isdigit(): curr_num=curr_num*10+ ord(ch)-ord('0') continue if operand=="+": #do the last operand captured when ch reaches current operand. in first run it is used to store the number for next iteration operation net+=last_num last_num=curr_num elif operand=="-": net+=last_num last_num=-curr_num elif operand=="*": last_num*=curr_num elif operand=="/": last_num=int(last_num/curr_num) operand,curr_num=ch,0 # for next iteration curr num is set 0 and current operand is caputured return net+last_num
basic-calculator-ii
90% faster||Simple|| O(1) Space O(N) Compution||Python
Avtansh_Sharma
0
7
basic calculator ii
227
0.423
Medium
4,137
https://leetcode.com/problems/basic-calculator-ii/discuss/2661136/Python-Simple-Solutions-Stack
class Solution: def calculate(self, s: str) -> int: stack, p, sign, total = [], 0, 1, 0 s = s.replace(" ","") while p < len(s): char = s[p] if char.isdigit(): num = "" while p < len(s) and s[p].isdigit(): num += s[p] p += 1 p -= 1 num = int(num) *sign total += num sign = 1 elif char in ['+', '-']: if stack: total *= stack.pop() total += stack.pop() if char == '-': sign = -1 stack.append(total) stack.append(sign) total, sign = 0, 1 elif char in ['*', '/']: p += 1 num = "" while p < len(s) and s[p].isdigit(): num += s[p] p += 1 p -= 1 if char == '*': total *= int(num) else: total /= int(num) total = int(total) p += 1 if len(stack) == 2: total *= stack.pop() total += stack.pop() return int(total)
basic-calculator-ii
✅ [Python] Simple Solutions Stack
Kofineka
0
50
basic calculator ii
227
0.423
Medium
4,138
https://leetcode.com/problems/basic-calculator-ii/discuss/2634824/Python3-or-Time-Limit-Exceeded
class Solution: def calculate(self, s: str) -> int: # Step 1: parse numbers. q = [] index = 0 while index < len(s): if s[index].isdigit(): if index == 0 or not s[index-1].isdigit(): q.append(int(s[index])) else: prev = q.pop(len(q) - 1) q.append(prev * 10 + int(s[index])) elif s[index] in ['+', '-', '*', '/']: q.append(s[index]) # Else ignore because its a space. index += 1 # Step 2: Handle multiply/divide. q2 = [] q2.append(q.pop(0)) while len(q) > 0: middle = q.pop(0) if middle == '*': left = q2.pop(len(q2) - 1) right = q.pop(0) q2.append(left * right) elif middle == '/': left = q2.pop(len(q2) - 1) right = q.pop(0) q2.append(int(left / right)) else: q2.append(middle) # Step 3: Handle add/minus. while len(q2) > 1: left = q2.pop(0) middle = q2.pop(0) right = q2.pop(0) if middle == "+": q2.insert(0, left + right) else: q2.insert(0, left - right) return q2[0]
basic-calculator-ii
Python3 | Time Limit Exceeded
mohsalim
0
10
basic calculator ii
227
0.423
Medium
4,139
https://leetcode.com/problems/basic-calculator-ii/discuss/2222838/Explanation-Python-Solution
class Solution: def calculate(self, s: str) -> int: if not s: return '0' stack=[] op = '+' num = 0 for e,i in enumerate(s): if i =="": # ignore spaces in string continue if i.isdigit(): num = num * 10 + int(i) # as string could be "0+123" this 123 will be append to the stack together. if i in "+-*/" or e==len(s)-1: # this e==len(s)-1 is because last char in string will be a number and we have to append it too. if op =='-': stack.append(-num) elif op=='+': stack.append(num) elif op=='*': stack.append(stack.pop()*num) else: stack.append(int(stack.pop()/num)) op=i num=0 #print(stack) return sum(stack)
basic-calculator-ii
Explanation Python Solution
aazad20
0
165
basic calculator ii
227
0.423
Medium
4,140
https://leetcode.com/problems/basic-calculator-ii/discuss/1938432/Python3-Solution
class Solution: def calculate(self, s: str) -> int: s = s.replace(" ", "") s += '+0' reduce = False stack = [] stack.append(s[0]) for i in range(1,len(s)): if s[i] in '+-': if reduce == False: stack.append(s[i]) else: a = int(stack.pop(-1)) op = stack.pop(-1) b = int(stack.pop(-1)) if op == '*': stack.append(a * b) else: stack.append(b // a) stack.append(s[i]) reduce = False elif s[i] in '*/': if reduce == False: stack.append(s[i]) else: a = int(stack.pop(-1)) op = stack.pop(-1) b = int(stack.pop(-1)) if op == '*': stack.append(a * b) else: stack.append(b // a) stack.append(s[i]) reduce = True else: if stack[-1] not in '+/-*': if stack[-1][0] != '0': stack[-1] += s[i] else: stack[-1] = s[i] else: stack.append(s[i]) stack.reverse() while stack: a = stack.pop(-1) op = stack.pop(-1) b = stack.pop(-1) if op == '-': stack.append(str(int(a) - int(b))) else: stack.append(str(int(b) + int(a))) try: x = stack[1] except IndexError: return stack[0]
basic-calculator-ii
Python3 Solution
DietCoke777
0
226
basic calculator ii
227
0.423
Medium
4,141
https://leetcode.com/problems/basic-calculator-ii/discuss/1865356/Python-slightly-suboptimal-for-intuition
class Solution: def __init__(self): self.operators = set(['*', '/', '+', '-']) def calculate(self, s: str) -> int: if not s: return 0 """ Step 1: Split the string into a list of numbers and operators, in the same order as they arrived in the string """ parsed = [] s_ptr = 0 while s_ptr < len(s): # case of operator if s[s_ptr] in self.operators: parsed.append(s[s_ptr]) s_ptr += 1 continue # case of number if s[s_ptr].isnumeric(): number_string = "" while s_ptr < len(s) and s[s_ptr].isnumeric(): number_string += s[s_ptr] s_ptr += 1 parsed.append(int(number_string)) continue # case of whitespace if s[s_ptr].isspace(): s_ptr += 1 continue # case of invalid input print("seen invalid char in input: " + s[s_ptr]) break # now parsed contains a list of numbers and operators """ Step 2: apply operations to numbers, using operator precedence. Examples 3+2*4 = 3+(2*4) = 11 2*4+3*3 = (2*4)+(3*3) = 17 2*4+3*3+2 = (2*4)+(3*3)+2 = 19 """ # create a list of numbers that will be summed at the end (essentially we are deferring computation of +/- operation til end) sum_list = [] cur_num = parsed.pop(0) cur_op = None for it in parsed: # case of operator if it in self.operators: # case of + or - if it == '+' or it == '-': sum_list.append(cur_num) cur_op = it # case of number if type(it) is int: # apply current operation to this number and current_num if cur_op == '+' or cur_op == '-': # we must have added the old cur_num to the list already. Now let's invert the current cur_num if it's occurring after a minus sign cur_num = it if cur_op == '+' else -it cur_op = None elif cur_op == '*': cur_num = it * cur_num else: # cur_op == '/' # remove sign while doing // otherwise you'll get the wrong result sign = -1 if cur_num < 0 else 1 cur_num = cur_num * sign cur_num = cur_num // it cur_num = cur_num * sign sum_list.append(cur_num) return sum(sum_list)
basic-calculator-ii
Python slightly suboptimal for intuition
scomathe
0
214
basic calculator ii
227
0.423
Medium
4,142
https://leetcode.com/problems/basic-calculator-ii/discuss/1647110/Python3-Solution-with-using-stack
class Solution: def calculate(self, s: str) -> int: _len = len(s) if _len == 0: return 0 current_num = 0 operation = '+' cur_char = '' stack = [] for i in range(_len): cur_char = s[i] if cur_char.isdigit(): current_num = (current_num * 10) + int(cur_char) if (not cur_char.isdigit() and not cur_char.isspace()) or i == _len - 1: if operation == '-': stack.append(-current_num) elif operation == '+': stack.append(current_num) elif operation == '*': elem = stack.pop() stack.append(elem * current_num) else: elem = stack.pop() if elem // current_num < 0 and elem % current_num != 0: stack.append(elem // current_num + 1) else: stack.append(elem // current_num ) current_num = 0 operation = cur_char res = 0 while stack: res += stack.pop() return res
basic-calculator-ii
[Python3] Solution with using stack
maosipov11
0
106
basic calculator ii
227
0.423
Medium
4,143
https://leetcode.com/problems/basic-calculator-ii/discuss/1646694/Python3-94.25-solution
class Solution: def calculate(self, s: str) -> int: """ :type s: str :rtype: int """ s += '#' s = s.replace(' ', '') stack = [] tmp = '' cur_op = '+' for i in s: if i in ['+', '-', '*', '/', '#']: if cur_op in ['+', '-']: stack.append(int(tmp) if cur_op == '+' else -int(tmp)) elif cur_op == '*': stack.append(stack.pop() * int(tmp)) else: stack.append(int(stack.pop()/int(tmp))) tmp = '' cur_op = i else: tmp += i return sum(stack)
basic-calculator-ii
Python3 94.25% solution
dolphin-plant
0
90
basic calculator ii
227
0.423
Medium
4,144
https://leetcode.com/problems/basic-calculator-ii/discuss/1418076/Easy-to-Read-and-Understand-Python
class Solution: def calculate(self, s: str) -> int: stack = [] i = 0 # Helper function to extract the numbers from input s. def get_num(): nonlocal i n = 0 while i < len(s) and (s[i].isdigit() or s[i] == ' '): if s[i] == ' ': i += 1 else: n = n*10 + int(s[i]) i += 1 return n while i < len(s): if s[i].isdigit(): stack.append(get_num()) elif s[i] == '-': i += 1 stack.append(-1*get_num()) elif s[i] == '+': i += 1 stack.append(get_num()) elif s[i] == '*': i += 1 stack.append(stack.pop()*get_num()) elif s[i] == '/': i += 1 if stack[-1] < 0: stack.append(-1* (abs(stack.pop()) // get_num())) else: stack.append(stack.pop() // get_num()) else: i += 1 return sum(stack)
basic-calculator-ii
Easy to Read and Understand Python
Pythagoras_the_3rd
0
282
basic calculator ii
227
0.423
Medium
4,145
https://leetcode.com/problems/basic-calculator-ii/discuss/947822/Basic-Calculator-II-or-python3-recursion-and-queue
class Solution: def calculate(self, s: str) -> int: def helper(q): ret, cur = None, '' while q: c = q.popleft() if c.isnumeric(): cur += c ret = int(cur) if c == '+': return ret + helper(q) if c == '-': cache = collections.deque([]) while q and q[0] not in ['+', '-']: cache.append(q.popleft()) ret -= helper(cache) if c in ['*', '/']: cache = q.popleft() while q and q[0].isnumeric(): cache += q.popleft() ret = ret * int(cache) if c =='*' else ret // int(cache) return ret if ret != None else int(cur) return helper(collections.deque(s))
basic-calculator-ii
Basic Calculator II | python3 recursion and queue
hangyu1130
0
43
basic calculator ii
227
0.423
Medium
4,146
https://leetcode.com/problems/basic-calculator-ii/discuss/750164/Python3-one-stack-and-two-stack-approach
class Solution: def calculate(self, s: str) -> int: op, val = "+", 0 #initialized at "+0" stack = [] for i, x in enumerate(s): if x.isdigit(): val = 10*val + int(x) #accumulating digits if x in "+-*/" or i == len(s) - 1: # if op == "+": stack.append(val) elif op == "-": stack.append(-val) elif op == "*": stack.append(stack.pop() * val) elif op == "/": stack.append(int(stack.pop()/val)) op, val = x, 0 #reset return sum(stack)
basic-calculator-ii
[Python3] one-stack & two-stack approach
ye15
0
126
basic calculator ii
227
0.423
Medium
4,147
https://leetcode.com/problems/basic-calculator-ii/discuss/750164/Python3-one-stack-and-two-stack-approach
class Solution: def calculate(self, s: str) -> int: #pre-processing to tokenize string s = s.replace(" ", "") #remove white space tokens = [] lo = hi = 0 while hi <= len(s): if hi == len(s) or s[hi] in "+-*/": tokens.append(s[lo:hi]) #tokenize number if hi < len(s): tokens.append(s[hi]) #tokenize operator lo = hi + 1 hi += 1 #dijkstra's two-stack algo opd, opr = [], [] #operand &amp; operator stacks sign = 1 for token in tokens: if token in "+-*/": opr.append(token) if token == "-": sign = -1 else: token = sign*int(token) sign = 1 if opr and opr[-1] in "*/": op = opr.pop() x = opd.pop() if op == "*": token = x * token elif op == "/": token = int(x / token) #not floor division opd.append(token) return sum(opd)
basic-calculator-ii
[Python3] one-stack & two-stack approach
ye15
0
126
basic calculator ii
227
0.423
Medium
4,148
https://leetcode.com/problems/summary-ranges/discuss/1805476/Python-Simple-Python-Solution-Using-Iterative-Approach-oror-O(n)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: start = 0 end = 0 result = [] while start < len(nums) and end<len(nums): if end+1 < len(nums) and nums[end]+1 == nums[end+1]: end=end+1 else: if start == end: result.append(str(nums[start])) start = start + 1 end = end + 1 else: result.append(str(nums[start])+'->'+str(nums[end])) start = end + 1 end = end + 1 return result
summary-ranges
[ Python ] ✔✔ Simple Python Solution Using Iterative Approach || O(n) 🔥✌
ASHOK_KUMAR_MEGHVANSHI
28
2,300
summary ranges
228
0.469
Easy
4,149
https://leetcode.com/problems/summary-ranges/discuss/1806040/Python-easy-O(n)-solution-or-explained
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans, i = [], 0 # take i to traverse the array, ans to fill the ranges while i < len(nums): # traverse the array lower = upper = nums[i] # for a range we need to find the upper and lower values while i < len(nums) and nums[i] == upper: # increment the i and upper as well in order to check they are equal. i += 1 upper += 1 ans.append(str(lower) + ("->" + str(upper-1) if upper-lower-1 else "")) # if upper-1 and lower both are equal append only lower, else append the range return ans
summary-ranges
✅ Python easy O(n) solution | explained
dhananjay79
4
377
summary ranges
228
0.469
Easy
4,150
https://leetcode.com/problems/summary-ranges/discuss/259553/Python-Easy-to-Understand
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: begin, res = 0, [] for i in range(len(nums)): if i + 1 >=len(nums) or nums[i+1]-nums[i] != 1: b = str(nums[begin]) e = str(nums[i]) res.append(b + "->" + e if b != e else b) begin = i + 1 return res
summary-ranges
Python Easy to Understand
ccparamecium
3
495
summary ranges
228
0.469
Easy
4,151
https://leetcode.com/problems/summary-ranges/discuss/2012883/Python-Clean-and-Simple!
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans, n = [], len(nums) start = 0 for i in range(1,n+1): if i == n or nums[i] != nums[i-1]+1: ans.append(self.helper(nums[start],nums[i-1])) start = i return ans def helper(self, a, b): return str(a) if a==b else str(a)+"->"+str(b)
summary-ranges
Python - Clean and Simple!
domthedeveloper
2
149
summary ranges
228
0.469
Easy
4,152
https://leetcode.com/problems/summary-ranges/discuss/1828014/6-Lines-Python-Solution-oror-65-Faster-oror-Memory-less-than-80
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans=[] ; i=0 ; nums.append(-1) for j in range(len(nums)-1): if nums[j+1]!=1+nums[j]: if i!=j: ans.append(str(nums[i])+'->'+str(nums[j])) ; i=j+1 else : ans.append(str(nums[i])) ; i=j+1 return ans
summary-ranges
6-Lines Python Solution || 65% Faster || Memory less than 80%
Taha-C
2
113
summary ranges
228
0.469
Easy
4,153
https://leetcode.com/problems/summary-ranges/discuss/1807510/Python-or-Runtime%3A-34-ms-faster-than-71.53-or-Memory-Usage%3A-13.8-MB-less-than-99.05
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return nums else: a=b=nums[0] out=[] for i in nums[1:]: if b == i-1: b = i else: if a!=b: out.append(str(a)+"->"+str(b)) else: out.append(str(a)) a=b=i if a!=b: out.append(str(a)+"->"+str(b)) else: out.append(str(a)) return out
summary-ranges
Python | Runtime: 34 ms, faster than 71.53% | Memory Usage: 13.8 MB, less than 99.05%
zouhair11elhadi
2
68
summary ranges
228
0.469
Easy
4,154
https://leetcode.com/problems/summary-ranges/discuss/1631073/Python-solution-single-pass
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: res=[] if len(nums)==0: return res ans=str(nums[0]) for i in range(1,len(nums)): if nums[i]!=nums[i-1]+1: if ans!=str(nums[i-1]): ans=ans+"->"+str(nums[i-1]) res.append(ans) ans=str((nums[i])) if ans!=str(nums[-1]): res.append(ans+"->"+str(nums[-1])) else: res.append(ans) return res
summary-ranges
Python solution single pass
diksha_choudhary
2
195
summary ranges
228
0.469
Easy
4,155
https://leetcode.com/problems/summary-ranges/discuss/1808671/Python3%3A-Easy-Solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: arr = [] n = len(nums) i = 0 while i<n: j = i while j<n-1 and (nums[j]+1)==nums[j+1]: j+=1 if i!=j: s = str(nums[i]) + "->" + str(nums[j]) arr.append(s) else: arr.append(str(nums[i])) i = j+1 return arr
summary-ranges
Python3: Easy Solution
deleted_user
1
44
summary ranges
228
0.469
Easy
4,156
https://leetcode.com/problems/summary-ranges/discuss/1806251/Python-Solution-(without-two-pointers-and-extra-function)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] res=[] s=str(nums[0]) for i in range(1,len(nums)): if nums[i]!=nums[i-1]+1: if int(s)==nums[i-1]: res.append(s) else: s+='->'+str(nums[i-1]) res.append(s) s=str(nums[i]) if int(s)==nums[-1]: res.append(s) else: s+='->'+str(nums[-1]) res.append(s) return res
summary-ranges
Python Solution (without two pointers and extra function)
amlanbtp
1
24
summary ranges
228
0.469
Easy
4,157
https://leetcode.com/problems/summary-ranges/discuss/1805413/Python-Simple-2-Pointer-Solution-with-Explanation
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums) == 0: return [] # Return for an empty list prev, n, result, i = nums[0], len(nums), [], 1 # At ith index we decide for prev to nums[i-1] while i < n: if nums[i] != nums[i-1] + 1: result.append(f"{prev}->{nums[i-1]}" if prev != nums[i-1] else f"{prev}") # Add the range or the individual value if start == end prev = nums[i] # Prev becomes current index i i += 1 result.append(f"{prev}->{nums[i-1]}" if prev != nums[i-1] else f"{prev}") # Add the range or the individual value if start == end. This one is done as the last value or last range was left out. return result
summary-ranges
Python Simple 2 Pointer Solution with Explanation
anCoderr
1
215
summary ranges
228
0.469
Easy
4,158
https://leetcode.com/problems/summary-ranges/discuss/1437025/Simple-or-Python3-or-Faster-than-99
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] start, curr, end = nums[0], nums[0], None res = list() for i in nums[1:]: curr += 1 if i == curr: end = i else: if not end: res.append(str(start)) else: res.append(str(start)+"->"+str(end)) start = i curr = i end = None # Handle Last element of the list. if not end: res.append(str(start)) else: res.append(str(start)+"->"+str(end)) return res
summary-ranges
Simple | Python3 | Faster than 99 %
deep765
1
170
summary ranges
228
0.469
Easy
4,159
https://leetcode.com/problems/summary-ranges/discuss/1389693/Easy-python-solution
class Solution: def makeInterval(self, start, end): return "{}->{}".format(start, end) if start != end else "{}".format(start) def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums) == 0: return [] else: ans = [] intervalStart = intervalEnd = nums[0] for i in range(1, len(nums)): if nums[i] == intervalEnd + 1: intervalEnd += 1 else: ans.append(self.makeInterval(intervalStart, intervalEnd)) intervalStart = intervalEnd = nums[i] ans.append(self.makeInterval(intervalStart, intervalEnd)) return ans
summary-ranges
Easy python solution
sp082d
1
97
summary ranges
228
0.469
Easy
4,160
https://leetcode.com/problems/summary-ranges/discuss/1247770/Python3-simple-easy-to-understand-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if nums == []: return [] l = [] x = y = nums[0] for i in range(1,len(nums)): if nums[i] == nums[i-1] + 1: y = nums[i] else: if x == y: l.append(f"{x}") else: l.append(f"{x}->{y}") x = y = nums[i] if x == y: l.append(f"{x}") else: l.append(f"{x}->{y}") return l
summary-ranges
Python3 simple, easy to understand solution
EklavyaJoshi
1
100
summary ranges
228
0.469
Easy
4,161
https://leetcode.com/problems/summary-ranges/discuss/914096/Python-O(N)-oror-Easy
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] res = [] l, r = 0, 1 while r < len(nums): if nums[r] == nums[r-1] + 1: r += 1 else: if r-l > 1: res.append(str(nums[l]) + '->' + str(nums[r-1])) if r-l == 1: res.append(str(nums[l])) l = r r += 1 if r-l > 1: res.append(str(nums[l]) + '->' + str(nums[r-1])) if r-l == 1: res.append(str(nums[l])) return res # TC: O(N) # SC: O(N)
summary-ranges
Python O(N) || Easy
airksh
1
34
summary ranges
228
0.469
Easy
4,162
https://leetcode.com/problems/summary-ranges/discuss/747779/Python3-linear-scan
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans = [] for i in range(len(nums)): if i == 0 or nums[i-1] + 1 != nums[i]: stack = [nums[i]] if i == len(nums)-1 or nums[i] + 1 != nums[i+1]: if stack[-1] != nums[i]: stack.append(nums[i]) ans.append(stack) return ["->".join(map(str, x)) for x in ans]
summary-ranges
[Python3] linear scan
ye15
1
64
summary ranges
228
0.469
Easy
4,163
https://leetcode.com/problems/summary-ranges/discuss/747779/Python3-linear-scan
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans = [] ii = 0 # start ptr for i in range(len(nums)): # end ptr if i+1 == len(nums) or nums[i] + 1 != nums[i+1]: # end of range if ii == i: ans.append(str(nums[i])) else: ans.append(str(nums[ii]) + "->" + str(nums[i])) ii = i + 1 return ans
summary-ranges
[Python3] linear scan
ye15
1
64
summary ranges
228
0.469
Easy
4,164
https://leetcode.com/problems/summary-ranges/discuss/314487/Python3Beats-99.64-easy-to-understand
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums)==0: return [] length=len(nums) start,end=0,0 ans=[] for i in range(length-1): if nums[i+1]==nums[i]+1: end=i+1 if nums[i+1]!=nums[i]+1: if start==end: ans.append(f"{nums[start]}") else: ans.append(f"{nums[start]}->{nums[end]}") start=i+1 end=i+1 if start==end: ans.append(f"{nums[-1]}") else: ans.append(f"{nums[start]}->{nums[-1]}") return ans
summary-ranges
[Python3]Beats 99.64% easy to understand
SunTX
1
102
summary ranges
228
0.469
Easy
4,165
https://leetcode.com/problems/summary-ranges/discuss/2844990/Python3-Solution-using-while-loop
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: i=0 if nums: prev_start = nums[0] else: prev_start = 0 range_lit =[] if len(nums)==1: range_lit.append(f"{nums[0]}") while i<len(nums)-1: #used "<" since we are comparing current and next characters if nums[i+1] == nums[i]+1: pass elif prev_start!=nums[i]: range_lit.append(f"{prev_start}->{nums[i]}") prev_start = nums[i+1] elif prev_start==nums[i]: range_lit.append(f"{nums[i]}") prev_start = nums[i+1] if i+1 == len(nums)-1 and prev_start==nums[i+1]: range_lit.append(f"{nums[i+1]}") elif i+1 == len(nums)-1 and prev_start!=nums[i+1]: range_lit.append(f"{prev_start}->{nums[i+1]}") i += 1 return range_lit
summary-ranges
Python3 Solution using while loop
vishnusuresh1995
0
2
summary ranges
228
0.469
Easy
4,166
https://leetcode.com/problems/summary-ranges/discuss/2834925/python-oror-simple-solution-oror-look-back
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: # if nums empty if not nums: return None ans = [str(nums[0])] # answer # go through nums for i in range(1, len(nums)): # new range if (nums[i] - nums[i - 1]) > 1: # range > 1 if str(nums[i - 1]) != ans[-1]: # end old range ans[-1] += f"->{nums[i - 1]}" # add new rage ans.append(str(nums[i])) # end last range if str(nums[-1]) != ans[-1]: ans[-1] += f"->{nums[-1]}" return ans
summary-ranges
python || simple solution || look back
wduf
0
2
summary ranges
228
0.469
Easy
4,167
https://leetcode.com/problems/summary-ranges/discuss/2826831/Python-time-O(N)-space-O(1)-detailed-explanation
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums) == 0: return "" elif len(nums) == 1: return [f'{nums[0]}'] out = [] start = 0 end = 0 for i in range(1,len(nums)): if nums[i] != nums[i-1] + 1: if start != end: out.append(f'{nums[start]}->{nums[end]}') else: out.append(f'{nums[start]}') start = i end = start else: end += 1 if start != end: out.append(f'{nums[start]}->{nums[end]}') else: out.append(f'{nums[start]}') return out
summary-ranges
Python time O(N), space O(1), detailed explanation
issabayevmk
0
10
summary ranges
228
0.469
Easy
4,168
https://leetcode.com/problems/summary-ranges/discuss/2807654/Easy-to-understand-python-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums) == 0: return [] output = [] start = nums[0] prev = nums[0] for i in range(1, len(nums)): num = nums[i] if prev + 1 == num: prev = num continue output.append(self.append_range(start, prev)) start = num prev = num output.append(self.append_range(start, prev)) return output def append_range(self, start, prev): if start == prev: return f'{start}' return f'{start}->{prev}'
summary-ranges
Easy to understand python solution
shanemmay
0
1
summary ranges
228
0.469
Easy
4,169
https://leetcode.com/problems/summary-ranges/discuss/2791789/Python-Two-pointer-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: res,left, right = [], 0,0 while right<len(nums): while right+1<len(nums) and nums[right]+1==nums[right+1]: right+=1 if nums[left]==nums[right]: res.append(f"{nums[left]}") else: res.append(f"{nums[left]}->{nums[right]}") right+=1 left = right return res
summary-ranges
Python - Two pointer solution
Flash017
0
3
summary ranges
228
0.469
Easy
4,170
https://leetcode.com/problems/summary-ranges/discuss/2785183/Python-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums)==0: return [] start, curr, end = nums[0], nums[0], None ans = [] for i in nums[1:]: curr+=1 if i==curr: end = i else: if end: ans.append(str(start)+"->"+str(end)) else: ans.append(str(start)) start = i curr = i end = None if end: ans.append(str(start)+"->"+str(end)) else: ans.append(str(start)) return ans
summary-ranges
Python solution
game50914
0
1
summary ranges
228
0.469
Easy
4,171
https://leetcode.com/problems/summary-ranges/discuss/2746541/Python3-Solution-O(N)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if nums == []: return [] first = last = nums[0] stack = [] for i in range(1, len(nums)): if nums[i] == last+1: last = nums[i] if i == len(nums)-1: stack.append(str(first)+"->"+str(last)) else: if first == last: stack.append(str(first)) else: stack.append(str(first)+"->"+str(last)) first = last = nums[i] if first == last: stack.append(str(first)) if not stack: stack.append(str(nums[0])) return stack
summary-ranges
Python3 Solution O(N)
paul1202
0
2
summary ranges
228
0.469
Easy
4,172
https://leetcode.com/problems/summary-ranges/discuss/2713629/Python-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans = [] i = 0 while i < len(nums): st = nums[i] while i + 1 < len(nums) and nums[i+1] == nums[i] + 1: i += 1 end = nums[i] if st == end: ans.append(f'{st}') else: ans.append(f'{st}->{end}') i += 1 return ans
summary-ranges
Python solution
kruzhilkin
0
5
summary ranges
228
0.469
Easy
4,173
https://leetcode.com/problems/summary-ranges/discuss/2691906/Python-solution-faster-than-99-using-Master-Slave-lists-(with-explanation)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: # Define some CORNER Cases # if len(nums) == 0: # Nothing to do if no integers are given return nums elif len(nums) == 1: # Nothing to do if single integer is given return list(map(str, nums)) else: # MAIN program begins only if 2(+) integers are provided. # 1st convert all integers to strings str_num_list = list(map(str, nums)) # Initiate 2 lists - Slave list constitutes the 1st element of the above list, while Master is initiated as blank list. slave_list = [str_num_list[0]] ; master_list = [] # Invoke a Lambda function to be used later. # The function appends the slave element to the master list if slave list only has a single element. # Otherwise, it clips the 1st and last element of the slave list, adds a "->" character in between them, and then appends this new element in the master list. add_2_master_list = lambda mlist, slist : mlist.append(slist[0] + str("->") + slist[-1]) if len(slist) > 1 else mlist.append(slist[0]) # Run a loop from 2nd element to last for i in str_num_list[1:]: # Check if reducing 1 from i doesn't gives us last element of slave list if int(i)-1 != int(slave_list[-1]): # If yes, invoke that lambda function &amp; start appending elements to the master list based on elements present in slave list add_2_master_list(master_list, slave_list) # Clear the slave_list to prepare for the next element slave_list.clear() # After every iteration, keep on appending the items in slave. Note : Slave must never be kept empty. slave_list.append(i) # Once all iterations are done, whatever items are there in the slave list have to be now added to the master list. # Hence again invoke the lambda function. add_2_master_list(master_list, slave_list) # Return the master list return master_list
summary-ranges
Python solution faster than 99% using Master-Slave lists (with explanation)
code_snow
0
7
summary ranges
228
0.469
Easy
4,174
https://leetcode.com/problems/summary-ranges/discuss/2678476/Python3-For-Loop-and-Helper-Function
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] output = [] def addToOutput(start, last): nonlocal output if last == start: output.append(f'{start}') else: output.append(f'{start}->{last}') start = nums[0] last = nums[0] for idx in range(1, len(nums)): num = nums[idx] if num != last+1: addToOutput(start, last) start = num last = num addToOutput(start, last) return output
summary-ranges
Python3 For Loop & Helper Function
Mbarberry
0
11
summary ranges
228
0.469
Easy
4,175
https://leetcode.com/problems/summary-ranges/discuss/2491668/Easy-Solution-for-beginners-oror-Python-3-oror-beats-97
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if nums == []: return [] res = [] start = nums[0] end = nums[0] i = 1 while i < len(nums): # print(nums[i]) if nums[i-1] + 1 == nums[i]: end += 1 else: res.append([start,end]) start = nums[i] end = nums[i] i += 1 res.append([start,end]) # print(res) for i in range(len(res)): [s,e] = res[i] if s == e: res[i] = str(s) else: res[i] = str(s) + '->' + str(e) return res
summary-ranges
Easy Solution for beginners || Python 3 || beats 97%
irapandey
0
91
summary ranges
228
0.469
Easy
4,176
https://leetcode.com/problems/summary-ranges/discuss/2240327/Easy-Python-solution.
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: s="" ans=[] if len(nums)==0: return ans if len(nums)==1: ans.append(str(nums[0])) return ans for i in range(len(nums)-1): if nums[i+1]!=nums[i]+1: s+=str(nums[i]) ans.append(s) s="" elif nums[i+1]==nums[i]+1 and s=="": s+=str(nums[i])+"->" s+=str(nums[len(nums)-1]) ans.append(s) return ans
summary-ranges
Easy Python solution.
imkprakash
0
103
summary ranges
228
0.469
Easy
4,177
https://leetcode.com/problems/summary-ranges/discuss/2066962/Dynamic-Sliding-Window-approach
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: left = 0 right = 0 range_arr = [] while left <= right < len(nums): if len(nums) - right > 1 and nums[right + 1] - nums[right] == 1: right = right + 1 else: if left == right: range_arr.append(str(nums[left])) else: range_arr.append(str(nums[left]) + "->" + str(nums[right])) right += 1 left = right return range_arr
summary-ranges
Dynamic Sliding Window approach
snagsbybalin
0
41
summary ranges
228
0.469
Easy
4,178
https://leetcode.com/problems/summary-ranges/discuss/1841144/Python-98.54-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] left, right = 0, 0 range_ls = [] while right != len(nums) - 1: if nums[right+1] - nums[right] == 1: right += 1 else: if left == right: range_ls.append(f"{nums[left]}") else: range_ls.append(f"{nums[left]}->{nums[right]}") left = right+1 right += 1 if left == right: range_ls.append(f"{nums[left]}") else: range_ls.append(f"{nums[left]}->{nums[right]}") return range_ls
summary-ranges
Python 98.54% solution
yusianglin11010
0
155
summary ranges
228
0.469
Easy
4,179
https://leetcode.com/problems/summary-ranges/discuss/1831402/Simple-Python-Solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums)==0: return [] ans=[] current='' flag=0 if len(nums)>0: current+=str(nums[0]) flag=0 for i in range(1, len(nums)): if nums[i]!=nums[i-1]+1: if flag: current+='->'+str(nums[i-1]) ans.append(current) current=str(nums[i]) flag=0 else: flag=1 if flag==1: current+='->'+str(nums[-1]) ans.append(current) else: ans.append(current) return ans
summary-ranges
Simple Python Solution
Siddharth_singh
0
88
summary ranges
228
0.469
Easy
4,180
https://leetcode.com/problems/summary-ranges/discuss/1807218/Python-easy-solution-O(n)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if len(nums) == 0: return [] ans = [] i = 0 start = nums[i] while i < len(nums)-1: if nums[i+1] != nums[i]+1: if nums[i] != start: s = str(start) + "->" + str(nums[i]) ans.append(s) start = nums[i+1] else: ans.append(str(start)) start = nums[i+1] i = i + 1 if nums[i-1]+1 == nums[i]: s = str(start) + "->" + str(nums[i]) ans.append(s) else: ans.append(str(nums[i])) return ans
summary-ranges
Python easy solution O(n)
abhiGamez
0
30
summary ranges
228
0.469
Easy
4,181
https://leetcode.com/problems/summary-ranges/discuss/1806871/Clean-solution-with-simple-logic-in-Python
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: def gen(): if not nums: return lo = hi = nums[0] fmt = lambda a, b: str(a) if a == b else f"{a}->{b}" for i in range(1, len(nums)): if nums[i] - nums[i - 1] == 1: hi = nums[i] else: yield fmt(lo, hi) lo = hi = nums[i] yield fmt(lo, hi) return list(gen())
summary-ranges
Clean solution with simple logic in Python
mousun224
0
27
summary ranges
228
0.469
Easy
4,182
https://leetcode.com/problems/summary-ranges/discuss/1806797/Simple-and-easy-O(N)-two-index
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: res = [] l = len(nums) i = j = 0 while i < l: while (j < l-1) and (nums[j] + 1) == nums[j+1]: j += 1 ni = str(nums[i]) res.append(ni+"->"+str(nums[j]) if i < j else ni) j += 1 i = j # print(i, j, res) return res
summary-ranges
Simple and easy, O(N), two index
coolshinji
0
13
summary ranges
228
0.469
Easy
4,183
https://leetcode.com/problems/summary-ranges/discuss/1806493/Python-faster-than-99
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: start,ans = 0,[] nums.append(1<<33) for i in range(1, len(nums)): if nums[i]-nums[i-1] != 1: if i-1 == start: ans.append(f"{nums[start]}") else: ans.append(f"{nums[start]}->{nums[i-1]}") start = i return ans
summary-ranges
Python, faster than 99%
zoro_55
0
20
summary ranges
228
0.469
Easy
4,184
https://leetcode.com/problems/summary-ranges/discuss/1806066/Python3-Solution-with-using-two-pointers
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: begin = end = 0 res = [] while end < len(nums): if end < len(nums) - 1 and nums[end + 1] == nums[end] + 1: end += 1 continue if begin == end: res.append(str(nums[end])) else: res.append(str(nums[begin]) + "->" + str(nums[end])) begin = end = end + 1 return res
summary-ranges
[Python3] Solution with using two-pointers
maosipov11
0
13
summary ranges
228
0.469
Easy
4,185
https://leetcode.com/problems/summary-ranges/discuss/1805911/Python3-Iterative-solution-using-a-single-for-loop-or-24-ms-beats-98
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] res = [] begin = nums[0] for i in range(1,len(nums)): if (nums[i] > nums[i-1] + 1): res.append((str(begin) + "->" + str(nums[i-1])) if begin != nums[i-1] else str(begin)) begin = nums[i] res.append((str(begin) + "->" + str(nums[-1])) if begin != nums[-1] else str(begin)) return res
summary-ranges
[Python3] Iterative solution using a single for loop | 24 ms beats 98%
nandhakiran366
0
12
summary ranges
228
0.469
Easy
4,186
https://leetcode.com/problems/summary-ranges/discuss/1805760/Python-O(N)-using-2-pointers
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: n = len(nums) nums.append(pow(2,32)) ret = [] i = 0 j = 1 while i < n: if nums[j - 1] == nums[j] - 1: j += 1 else: if j - i == 1: a = str(nums[i]) else: a = str(nums[i]) + "->" + str(nums[j - 1]) ret.append(a) i = j j = i + 1 return ret
summary-ranges
Python O(N) using 2 pointers
Aditya380
0
15
summary ranges
228
0.469
Easy
4,187
https://leetcode.com/problems/summary-ranges/discuss/1805408/Python-or-Sliding-window-or-Beats-98-or-With-comments
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: #BaseCase #1, if the length of nums is empty if len(nums) < 1: return [] #BaseCase #2, if the length of nums is 1 if len(nums) < 2: return [str(nums[0])] result = [] left = 0 #start element is used to track the beginning of a range value start = nums[left] right = 1 N = len(nums) #Looping over right value while right < N: #checking if the nums[right] is the neighbor of nums[left] if nums[left]+1 == nums[right]: left += 1 right += 1 #if they are not neighbors! else: if start == nums[left]: result.append(str(nums[left])) else: temp = str(start)+"->"+str(nums[left]) result.append(temp) start = nums[right] left = right right += 1 #if we are at the end of our nums if right == N: if nums[left] == start: result.append(str(nums[left])) return result else: temp = str(start)+"->"+str(nums[left]) result.append(temp) return result return result
summary-ranges
Python | Sliding window | Beats 98% | With comments
dee7
0
28
summary ranges
228
0.469
Easy
4,188
https://leetcode.com/problems/summary-ranges/discuss/1805306/Python3%3A-Two-pointers
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: output = [] left, right, n = 0, 1, len(nums) while right < n: while right < n and nums[right]-nums[right-1] == 1: right += 1 if left == right-1: output.append(str(nums[left])) else: output.append(str(nums[left]) + "->" + str(nums[right-1])) left = right right += 1 if left < n: output.append(str(nums[left])) return output
summary-ranges
Python3: Two pointers
schong3
0
51
summary ranges
228
0.469
Easy
4,189
https://leetcode.com/problems/summary-ranges/discuss/1720488/Python3-accepted-solution
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: li = [] lis = [] for i in range(len(nums)): if(lis == []): lis.append(str(nums[i])) if(i == len(nums)-1): if(lis[0]!=lis[-1]): li.append(lis[0]+"->"+lis[-1]) else: li.append(lis[0]) else: if(nums[i] == nums[i-1]+1): lis.append(str(nums[i])) if(i == len(nums)-1): if(lis[0]!=lis[-1]): li.append(lis[0]+"->"+lis[-1]) else: li.append(lis[0]) else: if(lis[0]!=lis[-1]): li.append(lis[0]+"->"+lis[-1]) else: li.append(lis[0]) lis = [] lis.append(str(nums[i])) if(i == len(nums)-1):li.append(lis[0]) return (li)
summary-ranges
Python3 accepted solution
sreeleetcode19
0
69
summary ranges
228
0.469
Easy
4,190
https://leetcode.com/problems/summary-ranges/discuss/1488282/Easy-Python3-Faster-than-95-with-Explanation-and-Code-Comments
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: # initiate result and a starter pointer res = [] start = None # iterate through the list keeping starter pointer at 0 # break when the sequence breaks, return starter + "->" + n # understand second if condition for above # if sequence breaks immediately after the starter, return just str(n) for i, n in enumerate(nums): if start is None: start = n if i == len(nums)-1 or nums[i+1]-n>1: res.append(str(start) + "->" + str(n) if n!=start else str(n)) start = None return res
summary-ranges
Easy Python3 Faster than 95% with Explanation and Code Comments
ajinkya2021
0
82
summary ranges
228
0.469
Easy
4,191
https://leetcode.com/problems/summary-ranges/discuss/1484055/Python-O(n)-time-O(1)-space-100-faster
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: n = len(nums) res = [] if n ==0: return [] if n ==1: return [str(nums[0])] start, end = 0, 0 while end <= n-1: if end == n-1: if start == end: res.append(str(nums[start])) else: res.append(str(nums[start]) + "->" + str(nums[end])) break else: # end < n-1 while end < n-1 and nums[end+1] == nums[end] + 1: end += 1 if start == end: res.append(str(nums[start])) else: res.append(str(nums[start]) + "->" + str(nums[end])) end +=1 start = end return res
summary-ranges
Python O(n) time O(1) space, 100% faster
byuns9334
0
118
summary ranges
228
0.469
Easy
4,192
https://leetcode.com/problems/summary-ranges/discuss/1443028/Python3-Faster-Than-99.08
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] if len(nums) == 1: return [str(nums[0])] d, start, i = {}, nums[0], 1 d[nums[0]] = nums[0] while i < len(nums): if nums[i] - nums[i - 1] == 1: d[start] = nums[i] i += 1 else: start = nums[i] d[start] = start i += 1 nums = sorted(d.items(), key = lambda x : x[0]) d = [] for i in nums: if i[0] == i[1]: d.append(str(i[0])) else: d.append(str(i[0]) + "->" + str(i[1])) return d
summary-ranges
Python3 Faster Than 99.08%
Hejita
0
100
summary ranges
228
0.469
Easy
4,193
https://leetcode.com/problems/summary-ranges/discuss/1421022/One-pass-94-speed
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: len_nums = len(nums) if not len_nums: return [] elif len_nums == 1: return [f"{nums[0]}"] ans = [] start = nums[0] for i in range(len_nums - 1): if nums[i + 1] - nums[i] > 1: if nums[i] > start: ans.append(f"{start}->{nums[i]}") else: ans.append(f"{start}") start = nums[i + 1] if nums[-1] > start: ans.append(f"{start}->{nums[-1]}") else: ans.append(f"{start}") return ans
summary-ranges
One pass, 94% speed
EvgenySH
0
154
summary ranges
228
0.469
Easy
4,194
https://leetcode.com/problems/summary-ranges/discuss/1401053/Very-Interesting-Question!!
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: def helper(start,end): if end != start: return str(start) + '->' + str(end) else: return str(start) res = [] if len(nums) == 0: return [] if len(nums) == 1: res.append(helper(nums[0],nums[0])) return res cur, start = nums[0],nums[0] for index, num in enumerate(nums[1:]): if num - 1 == cur: cur = num else: res.append(helper(start,cur)) start,cur = num,num res.append(helper(start,cur)) return res
summary-ranges
Very Interesting Question!!
yjin232
0
34
summary ranges
228
0.469
Easy
4,195
https://leetcode.com/problems/summary-ranges/discuss/1313172/PYTHON-3
class Solution: def summaryRanges(self, a: List[int]) -> List[str]: if not a: return [] ans=[] n=len(a) start=a[0] flag=0 for i in range(n-1): if a[i]+1==a[i+1]: flag=1 else: if flag==1 and start!=a[i]: ans.append(str(start)+'->'+str(a[i])) else: ans.append(str(start)) start=a[i+1] if flag==1 and start!=a[i+1]: ans.append(str(start)+'->'+str(a[i+1])) else: ans.append(str(start)) return ans
summary-ranges
[PYTHON 3]
jiteshbhansali
0
66
summary ranges
228
0.469
Easy
4,196
https://leetcode.com/problems/majority-element-ii/discuss/1483430/Python-95-faster-in-speed
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: return [x for x in set(nums) if nums.count(x) > len(nums)/3]
majority-element-ii
Python // 95% faster in speed
fabioo29
3
394
majority element ii
229
0.442
Medium
4,197
https://leetcode.com/problems/majority-element-ii/discuss/2827995/in-n-time-complexity-usind-defaultdict
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: dc=defaultdict(lambda:0) n=len(nums)//3 for a in nums: dc[a]+=1 ans=[] for a in dc: if(dc[a]>n): ans.append(a) return ans
majority-element-ii
in n time complexity usind defaultdict
droj
2
46
majority element ii
229
0.442
Medium
4,198
https://leetcode.com/problems/majority-element-ii/discuss/2751224/python3ororo(n)
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: d=dict() k=len(nums)//3 a=[] for i in nums: if i in d: d[i]+=1 else: d[i]=1 for i in nums: if d[i]>k and i not in a: a.append(i) return a
majority-element-ii
python3||o(n)
Sneh713
2
188
majority element ii
229
0.442
Medium
4,199