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/beautiful-arrangement-ii/discuss/1574163/Python3-Solution-or-100-faster-or-4-line-code
class Solution: def constructArray(self, n: int, k: int) -> List[int]: result = list(range(1,n+1)) result[0 : k+1 : 2] = list(range(1,(k+2)//2 + 1)) result[1 : k+1 : 2] = list(range(k+1,(k+2)//2,-1)) return result
beautiful-arrangement-ii
Python3 Solution | 100% faster | 4-line code
satyam2001
0
85
beautiful arrangement ii
667
0.597
Medium
11,100
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1447565/Python3-solution
class Solution: def constructArray(self, n: int, k: int) -> List[int]: l,h = 1,n res = [l] l += 1 while k > 1: res.append(h) h -= 1 k -= 1 if k > 1: res.append(l) l += 1 k -= 1 if res[-1] == h+1: res += list(range(h,l-1,-1)) else: res += list(range(l,h+1)) return res
beautiful-arrangement-ii
Python3 solution
EklavyaJoshi
0
41
beautiful arrangement ii
667
0.597
Medium
11,101
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1154660/Python3-Simple-to-understand-Greedy-Approach
class Solution: def constructArray(self, n: int, k: int) -> List[int]: solution = [1] offset = k currentSign = 1 while abs(offset) >= 1: if currentSign == 1: solution.append(solution[-1] + offset) currentSign = 0 else: solution.append(solution[-1] - offset) currentSign = 1 offset -= 1 for i in range(1, n+1): if i not in solution: solution.append(i) return solution
beautiful-arrangement-ii
[Python3] Simple to understand, Greedy Approach
karanpitt
0
70
beautiful arrangement ii
667
0.597
Medium
11,102
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/388331/Simon's-Note-Python3
class Solution: def constructArray(self, n: int, k: int) -> List[int]: t=[i for i in range(1,n+1)] for j in range(1,k): t[j:]=t[j:][::-1] return t
beautiful-arrangement-ii
[🎈Simon's Note🎈] Python3
SunTX
0
112
beautiful arrangement ii
667
0.597
Medium
11,103
https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/1581461/Binary-Search-Solution-with-detailed-explanation-beating-98-in-time-and-86-in-space
class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: # special cases: k == 1, k == m * n if k == 1: return 1 if k == m * n: return m * n # make the matrix a tall one - height >= width # because later I will loop along the width. This will reduce the time if n >= m: m, n = n, m # set the left, right boundaries and the ranks (the largest ranks for the values) # e.g. in a 3 * 3 table, number 2 shows up twice, taking up ranks from 2 to 3 # so the largest rank here is 3 for number 2. left = 1 # left_rank = 1 right = m * n # right_rank = m * n # binary search loop while right - left > 1: mid = (left + right) // 2 # mid_rank is the largest rank of the number mid_rank = 0 # find the number of columns whose maximum < mid # (mid - 1) is to prevent counting the column with maximum == mid. num_cols = (mid - 1) // m residual = mid - num_cols * m mid_rank += num_cols * m # flag to track if mid is a valid value in the table flag = 0 for i in range(num_cols + 1, n + 1): if i == mid: mid_rank += 1 break else: mid_rank += mid // i if mid % i == 0: flag = 1 if flag == 1: # mid is a valid number in the table # if mid_rank == k: mid's largest rank is k and mid is the kth number # if mid_rank < k: kth number > mid, so left = mid # if mid_rank > k: mid's largest rank > k but mid still can be the kth number but kth number can be no larger than mid, so right = mid if mid_rank == k: return mid elif mid_rank > k: right = mid else: left = mid else: # mid is not a valid number in the table # if mid_rank == k, it means there are k values in the table smaller than mid # so there is a number smaller than mid ranking the kth. # mid_rank > k or mid_rank < k: similar operation as above if mid_rank >= k: right = mid else: left = mid # In case the while loop breaks out without returning # let's assume when right - left == 2 and mid == left + 1. The solution must be among the three. # right with its largest rank > k # left with its largest rank < k # Scenario 1. if mid is a valid number in the table ## 1a. if mid_rank < k: right has its rank from mid_rank + 1 (<= k) till right_rank (> k) ## 1b. if mid_rank > k: right = mid. Now right (== mid) has its rank from left_rank + 1 (<= k) till mid_rank (> k) ## in both cases, right is the solution # Scenario 2. if mid is not a valid number in the table then we can just ignore mid and imply the solution is right. ## But step by step, as mid is not in the table, mid_rank == left_rank, so left = mid. ## So right has its rank from mid_rank + 1 (i.e. left_rank + 1) (<= k) till right_rank (> k). right is the solution. return right
kth-smallest-number-in-multiplication-table
Binary Search Solution with detailed explanation, beating 98% in time and 86% in space
leonine9
1
83
kth smallest number in multiplication table
668
0.515
Hard
11,104
https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/1342158/Python3-binary-search
class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: lo, hi = 1, m*n while lo < hi: mid = lo + hi >> 1 cnt = sum(min(n, mid//(i+1)) for i in range(m)) if cnt < k: lo = mid + 1 else: hi = mid return lo
kth-smallest-number-in-multiplication-table
[Python3] binary search
ye15
1
99
kth smallest number in multiplication table
668
0.515
Hard
11,105
https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/1580515/TLE-Python3-Dijkstra's-algorithm
class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: pq = [(1, 1, 1)] # Priority queue (table[i][j], i, j) seen = set((1,1)) # Visited nodes # Traverse the first k-1 nodes for i in range(1, k): # Pop ith smallest node cur, a, b = heappop(pq) # Add right node if it hasn't been seen to pq if a < m and (a+1, b) not in seen: heappush(pq, (cur+b, a+1, b)) seen.add((a+1, b)) # Add left node if it hasn't been seen to pq if b < n and (a, b+1) not in seen: heappush(pq, (cur+a, a, b+1)) seen.add((a, b+1)) # Next node in priority queue is the kth smallest node return heappop(pq)[0]
kth-smallest-number-in-multiplication-table
TLE [Python3] Dijkstra's algorithm
vscala
0
118
kth smallest number in multiplication table
668
0.515
Hard
11,106
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1046286/Python.-faster-than-98.05.-recursive.-6-lines.-DFS.
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: if not root: return root if root.val < low: return self.trimBST(root.right, low, high) if root.val > high: return self.trimBST(root.left, low, high) root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
Python. faster than 98.05%. recursive. 6 lines. DFS.
m-d-f
24
1,000
trim a binary search tree
669
0.663
Medium
11,107
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1951579/python3-oror-10-line-self-recursive
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if not root: return None if root.val > high: return self.trimBST(root.left, low, high) if root.val < low: return self.trimBST(root.right, low, high) root.left = self.trimBST(root.left, low, root.val) root.right = self.trimBST(root.right, root.val, high) return root
trim-a-binary-search-tree
python3 || 10-line self recursive
gulugulugulugulu
1
25
trim a binary search tree
669
0.663
Medium
11,108
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1949450/Python-Easy-Python-Solution-Using-Recursion
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def TrimBST(node): if node == None: return None elif node.val > high : return TrimBST(node.left) elif node.val < low : return TrimBST(node.right) else: node.left = TrimBST(node.left) node.right = TrimBST(node.right) return node return TrimBST(root)
trim-a-binary-search-tree
[ Python ] ✅✅ Easy Python Solution Using Recursion ✌🥳
ASHOK_KUMAR_MEGHVANSHI
1
38
trim a binary search tree
669
0.663
Medium
11,109
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1947870/python3-recursion-easy-to-read
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if root is None: return None if low <= root.val <= high: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) elif root.val < low: root = self.trimBST(root.right, low, high) else: root = self.trimBST(root.left, low, high) return root
trim-a-binary-search-tree
python3 recursion easy-to-read
user2613C
1
59
trim a binary search tree
669
0.663
Medium
11,110
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1924346/Python-Elegant-Clean-Recursive-Solution-or-with-Comments-or-Time-and-Space-Complexity%3A-O(n)
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: # base case if not root: return # trim left and right subtree root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) # if node's value is out of bounds # we appropriately replace the current node if root.val < low: root = root.right elif root.val > high: root = root.left return root
trim-a-binary-search-tree
[Python] Elegant Clean Recursive Solution | with Comments | Time & Space Complexity: O(n)
ysingla
1
43
trim a binary search tree
669
0.663
Medium
11,111
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1411985/Python-Solution-Beats-100-time-w-Comments
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def recur(root): if root is None: return None #if root is larger than boundary, then we must return the next child that's within the boundary #in this case, only children to the left have a chance of working. if root.val > high: return recur(root.left) #if root is smaller than boundary, then we must return the next child that's within the boundary #in this case, only children to the right have a chance of working. elif root.val < low: return recur(root.right) #if the root falls within the boundary, assign their pointers to the next children that work. else: root.left = recur(root.left) root.right = recur(root.right) #if the root fell in the boundary, then return for previous recursive call to use. return root return recur(root)
trim-a-binary-search-tree
Python Solution Beats 100% time w/ Comments
mguthrie45
1
89
trim a binary search tree
669
0.663
Medium
11,112
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1110051/Python-or-Recursion-or-Faster-99
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: def rec(root): if root: if not(low<=root.val<=high): if root.val<low: return rec(root.right) return rec(root.left) else: root.left,root.right=rec(root.left),rec(root.right) return root return rec(root)
trim-a-binary-search-tree
Python | Recursion | Faster 99%
rajatrai1206
1
117
trim a binary search tree
669
0.663
Medium
11,113
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1046702/Python-easy-solution-or-93-faster-or-Recursion
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: def helper_trim(node): if node is None: return node elif node.val > high: return self.trimBST(node.left) elif node.val < low: return self.trimBST(node.right) else: node.left = self.trimBST(node.left) node.right = self.trimBST(node.right) return node return helper_trim(root) If you get it please upvote
trim-a-binary-search-tree
Python easy solution | 93% faster | Recursion
vsahoo
1
93
trim a binary search tree
669
0.663
Medium
11,114
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/2492442/Python-runtime-64.38-memory-42.23-with-explanation
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if not root: return None elif low <= root.val <= high: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root elif root.val < low: return self.trimBST(root.right, low, high) elif root.val > high: return self.trimBST(root.left, low, high)
trim-a-binary-search-tree
Python, runtime 64.38%, memory 42.23% with explanation
tsai00150
0
28
trim a binary search tree
669
0.663
Medium
11,115
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1958095/Python-solution-Pre-order%2B-Construct-BST
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: nodes = [] def preorder(node): if node is None: return nodes.append(node) preorder(node.left) preorder(node.right) preorder(root) head = None for i in range(len(nodes)): if nodes[i].val < low or nodes[i].val > high: continue new_node = TreeNode(val=nodes[i].val) if head is None: head = new_node else: prev_node, cur_node = None, head while cur_node: prev_node = cur_node if nodes[i].val > cur_node.val: cur_node = cur_node.right else: cur_node = cur_node.left if prev_node.val > nodes[i].val: prev_node.left = new_node else: prev_node.right = new_node return head
trim-a-binary-search-tree
Python solution, Pre order+ Construct BST
pradeep288
0
14
trim a binary search tree
669
0.663
Medium
11,116
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1952643/Explained-Python-Simple-Solution-with-comments-O(n)-time-O(1)-space-80-time-80-memory
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: return trim(root, low, high) def trim(node, low, high): # node is empty if node is None: return None # node is a leaf (no children) if node.left is None and node.right is None: if low <= node.val <= high: return node return None # Apply the trim function on the left subtree and get the trimmed left subtree left = trim(node.left, low, high) # Similarly, trim the right subtree right = trim(node.right, low, high) # If the node values is within the limits, create a new tree with the current node and modified left and right subtrees of this node if low <= node.val <= high: node.left, node.right = left, right return node # If the node value is less than the lower limit, we excluse the node value. # Also note that all the values in the left subtree are less than the node. So, we remove the left subtree. # What remains is the right subtree elif node.val < low: return right # Similarly, here the node is greater than the upper limit. So the entire right subtree is also greater than the upper limit # What remains is the left sub tree elif node.val > high: return left return None
trim-a-binary-search-tree
[Explained] [Python] Simple Solution with comments O(n) time O(1) space [80% time 80% memory]
akhileshravi
0
12
trim a binary search tree
669
0.663
Medium
11,117
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1951321/Recursion-and-Iterative-or-Python3
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def trim(root: Optional[TreeNode]): if root is None: return None if root.val < low: return trim(root.right) elif root.val > high: return trim(root.left) else: root.left = trim(root.left) root.right = trim(root.right) return root return trim(root)
trim-a-binary-search-tree
Recursion and Iterative | Python3
qihangtian
0
7
trim a binary search tree
669
0.663
Medium
11,118
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1951321/Recursion-and-Iterative-or-Python3
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: # trim to root while root is not None: if root.val > high: root = root.left elif root.val < low: root = root.right else: break if root is None: return None # trim left parent = root node = root.left while node is not None: if node.val < low: parent.left = node.right node = node.right else: parent = node node = node.left parent.left = None # trim right parent = root node = root.right while node is not None: if node.val > high: parent.right = node.left node = node.left else: parent = node node = node.right parent.right = None return root
trim-a-binary-search-tree
Recursion and Iterative | Python3
qihangtian
0
7
trim a binary search tree
669
0.663
Medium
11,119
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1949721/Python3-Simple-DFS-solution-or-40ms-faster-than-99.61-or-18-MB-less-than-83.03
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def dfs(node): if not node: return if low <= node.val <= high: node.left = dfs(node.left) node.right = dfs(node.right) return node elif node.val < low: return dfs(node.right) else: return dfs(node.left) return dfs(root) ```
trim-a-binary-search-tree
[Python3] Simple DFS solution | 40ms faster than 99.61% | 18 MB, less than 83.03%
nandhakiran366
0
8
trim a binary search tree
669
0.663
Medium
11,120
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1949538/Python-Solution
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if root is None: return root root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) if low <= root.val <= high: return root if root.right: return root.right return root.left
trim-a-binary-search-tree
✅ Python Solution
dhananjay79
0
19
trim a binary search tree
669
0.663
Medium
11,121
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948813/Python-or-Recursion-or-Beats-98
class Solution(object): def trimBST(self, root, low, high): """ :type root: TreeNode :type low: int :type high: int :rtype: TreeNode """ if not root: return elif root.val < low: return self.trimBST(root.right, low, high) elif root.val > high: return self.trimBST(root.left, low, high) root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
Python | Recursion | Beats 98%
prajyotgurav
0
19
trim a binary search tree
669
0.663
Medium
11,122
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948372/669.-Trim-a-Binary-Search-Tree
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if(root is None): return None elif(root.val > high): return self.trimBST(root.left, low, high) elif(root.val < low): return self.trimBST(root.right, low, high) else: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
669. Trim a Binary Search Tree
shubham_pcs2012
0
6
trim a binary search tree
669
0.663
Medium
11,123
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948239/Python3-simple-recursion(Beats-~96)
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if not root: return None if low<=root.val<=high: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) elif root.val < low: return self.trimBST(root.right, low, high) elif root.val > high: return self.trimBST(root.left, low, high) return root
trim-a-binary-search-tree
✔️Python3-simple recursion(Beats ~96%)
constantine786
0
14
trim a binary search tree
669
0.663
Medium
11,124
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948092/Fastest-python-solution-with-comments.-99.61-faster
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if root == None: return None ''' Invalid node Ignore entire left subtree of this node and return the root of trimmed right subtree ''' if root.val < low: return self.trimBST(root.right, low, high) ''' Invalid node Ignore entire left subtree of this node and return the root of trimmed left subtree ''' if root.val > high: return self.trimBST(root.left, low, high) ''' The current node is valid. So trim the left subtree and assign it to its left child and trim the right subtree and assign it to its right child ''' root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
Fastest python solution with comments. 99.61% faster
souravrane_
0
14
trim a binary search tree
669
0.663
Medium
11,125
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948031/Python-Double-beats-100-solution
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if not root : return None if root.val < low : root = self.trimBST(root.right, low, high) elif root.val > high : root = self.trimBST(root.left, low, high) else: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
[Python] Double beats 100% solution
crazypuppy
0
7
trim a binary search tree
669
0.663
Medium
11,126
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1948027/Clean-recursive-DFS-in-Python-and-C
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def helper(n: TreeNode = root) -> TreeNode: if not n: return None if n.val < low: return helper(n.right) if n.val > high: return helper(n.left) n.left, n.right = map(helper, (n.left, n.right)) return n return helper()
trim-a-binary-search-tree
Clean recursive DFS in Python and C
mousun224
0
9
trim a binary search tree
669
0.663
Medium
11,127
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1547637/Python3
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def trim(root): if not root: return None if root.val < low: return trim(root.right) if root.val > high: return trim(root.left) root.left = trim(root.left) root.right = trim(root.right) return root return trim(root)
trim-a-binary-search-tree
Python3
immutable_23
0
32
trim a binary search tree
669
0.663
Medium
11,128
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1481715/Python-Clean-Postorder-DFS
class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def trim(node = root): if not node: return None L, R = trim(node.left), trim(node.right) if node.val < low: return R elif high < node.val: return L node.left, node.right = L, R return node return trim()
trim-a-binary-search-tree
[Python] Clean Postorder DFS
soma28
0
48
trim a binary search tree
669
0.663
Medium
11,129
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1429430/Python3-Recursive-DFS-two-possible-solutions
class Solution: def traversal(self, node, low, high): if not node: return (False, None) l_is_out, l = self.traversal(node.left, low, high) r_is_out, r = self.traversal(node.right, low, high) if l_is_out: node.left = l if r_is_out: node.right = r if node.val < low or node.val > high: return (True, l or r) return (False, node) def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: is_out, child = self.traversal(root, low, high) if is_out: return child return root
trim-a-binary-search-tree
[Python3] Recursive DFS two possible solutions
maosipov11
0
43
trim a binary search tree
669
0.663
Medium
11,130
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1429430/Python3-Recursive-DFS-two-possible-solutions
class Solution: def traversal(self, node, low, high): if not node: return None if node.val < low: return self.traversal(node.right, low, high) elif node.val > high: return self.traversal(node.left, low, high) node.left = self.traversal(node.left, low, high) node.right = self.traversal(node.right, low, high) return node def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: return self.traversal(root, low, high)
trim-a-binary-search-tree
[Python3] Recursive DFS two possible solutions
maosipov11
0
43
trim a binary search tree
669
0.663
Medium
11,131
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1249170/Simple-Recursive-Solution-or-Python
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: if not root: return root # Trim right sub-tree if root.val < low: return self.trimBST(root.right, low, high) # Trim left sub-tree if root.val > high: return self.trimBST(root.left, low, high) # Trim both sides root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
trim-a-binary-search-tree
Simple Recursive Solution | Python
shubh_027
0
64
trim a binary search tree
669
0.663
Medium
11,132
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1052079/Python-Solution
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: ###### 1############## def inrange(val): if val<low or val>high: return False return True def rec(node): if node == None: return None lnode = rec(node.left) rnode = rec(node.right) if inrange(node.val)==False: ####### 2 ############# if rnode: node.val = rnode.val node.left = rnode.left node.right = rnode.right rnode = None ######### 3 ######### elif lnode: node.val = lnode.val node.left = lnode.left node.right = lnode.right lnode = None else: ##### 4 ##### return None else: ##### 5 #### node.left = lnode node.right = rnode return node return rec(root)
trim-a-binary-search-tree
Python Solution
SaSha59
0
105
trim a binary search tree
669
0.663
Medium
11,133
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1047130/Iteration-Version-O-(log(N))-Trimming-while-Doing-Binary-Search-Without-Stack
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: head = TreeNode(left=root) # Guard Node pre, cur = head, head.left # Binary search for low while cur: if cur.val > low: pre = cur cur = cur.left elif cur.val < low: # trim nodes less than low cur = cur.right pre.left = cur else: cur.left = None break head.right = head.left pre, cur = head, head.right # Binary search for high while cur: if cur.val < high: pre = cur cur = cur.right elif cur.val > high: # trim nodes larger than high cur = cur.left pre.right = cur else: cur.right = None break return head.right
trim-a-binary-search-tree
Iteration Version O (log(N))- Trimming while Doing Binary Search - Without Stack
milileetcode
0
74
trim a binary search tree
669
0.663
Medium
11,134
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1046589/Python-DFS-Post-Order-4-lines
class Solution: def trimBST(self, root, low, high): if not root: return None root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root if low <= root.val <= high else root.left or root.right
trim-a-binary-search-tree
[Python] DFS Post-Order 4 lines
reeestandard
0
49
trim a binary search tree
669
0.663
Medium
11,135
https://leetcode.com/problems/trim-a-binary-search-tree/discuss/487298/Python-Iterative-solution
class Solution: def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode: # iterative if root is None: return None while root and (root.val < L or root.val > R): if root.val < L: root = root.right else: root = root.left lnode = rnode = root while lnode.left: if lnode.left.val < L: lnode.left = lnode.left.right else: lnode = lnode.left while rnode.right: if rnode.right.val > R: rnode.right = rnode.right.left else: rnode = rnode.right return root
trim-a-binary-search-tree
Python Iterative solution
Kingfisher
0
141
trim a binary search tree
669
0.663
Medium
11,136
https://leetcode.com/problems/maximum-swap/discuss/846837/Python-3-or-Greedy-Math-or-Explanations
class Solution: def maximumSwap(self, num: int) -> int: s = list(str(num)) n = len(s) for i in range(n-1): # find index where s[i] < s[i+1], meaning a chance to flip if s[i] < s[i+1]: break else: return num # if nothing find, return num max_idx, max_val = i+1, s[i+1] # keep going right, find the maximum value index for j in range(i+1, n): if max_val <= s[j]: max_idx, max_val = j, s[j] left_idx = i # going right from i, find most left value that is less than max_val for j in range(i, -1, -1): if s[j] < max_val: left_idx = j s[max_idx], s[left_idx] = s[left_idx], s[max_idx] # swap maximum after i and most left less than max return int(''.join(s)) # re-create the integer
maximum-swap
Python 3 | Greedy, Math | Explanations
idontknoooo
43
3,600
maximum swap
670
0.479
Medium
11,137
https://leetcode.com/problems/maximum-swap/discuss/1623820/Python-3-O(n)-time-O(1)-space-without-using-strings-with-comments
class Solution: def maximumSwap(self, num: int) -> int: # larger digit to swap, digit position of this digit high_digit = high_pos = 0 # smaller digit to swap, digit position of this digit low_digit = low_pos = 0 # greatest digit seen so far, digit postion of this digit cur_high_digit, cur_high_pos = -1, 0 # current digit position pos = 1 res = num while num: # iterate through digits from right to left digit = num % 10 # if digit is greatest digit yet if digit > cur_high_digit: cur_high_digit, cur_high_pos = digit, pos # if digit is less than greatest digit yet elif digit < cur_high_digit: # set the digits to swap as the greatest digit yet, and this digit high_digit, high_pos = cur_high_digit, cur_high_pos low_digit, low_pos = digit, pos pos *= 10 num //= 10 # swap the digits res += high_digit*(low_pos - high_pos) + low_digit*(high_pos - low_pos) return res
maximum-swap
Python 3 O(n) time, O(1) space, without using strings, with comments
dereky4
7
889
maximum swap
670
0.479
Medium
11,138
https://leetcode.com/problems/maximum-swap/discuss/1548210/Python3-O(n)-time-solution
class Solution: def maximumSwap(self, num: int) -> int: nums = [int(x) for x in str(num)] _max = -1 _max_idx = 0 last_max_idx, last_min_idx = 0, 0 for idx in range(len(nums) - 1, -1, -1): if nums[idx] > _max: _max = nums[idx] _max_idx = idx elif nums[idx] < _max: last_min_idx = idx last_max_idx = _max_idx nums[last_max_idx], nums[last_min_idx] = nums[last_min_idx], nums[last_max_idx] return int(''.join([str(num) for num in nums]))
maximum-swap
[Python3] O(n) time solution
maosipov11
2
383
maximum swap
670
0.479
Medium
11,139
https://leetcode.com/problems/maximum-swap/discuss/2695571/Python-Hash-table-O(n)-or-O(1)
class Solution: def maximumSwap(self, num: int) -> int: num = [int(i) for i in str(num)] dit = defaultdict(int) for i, n in enumerate(num): dit[n] = max(dit[n], i) flag = False for i, n in enumerate(num): for x in range(9, n, -1): if x in dit and dit[x] > i: num[i], num[dit[x]] = num[dit[x]], num[i] flag = True break if flag: break return int(''.join(str(i) for i in num))
maximum-swap
Python Hash table O(n) | O(1)
scr112
1
119
maximum swap
670
0.479
Medium
11,140
https://leetcode.com/problems/maximum-swap/discuss/1452761/PyPy3-A-bit-slower-but-simple-solution-w-comments
class Solution: def maximumSwap(self, num: int) -> int: # Init max_num = num # Conver num to string s = list(str(num)) n = len(s) # Loop for each condition for i in range(n): for j in range(i+1, n): # Swap i and j s[i], s[j] = s[j], s[i] # Calc max from the string max_num = max(max_num, int(''.join(s))) # Re-Swap i and j, to restore the orginal list s[i], s[j] = s[j], s[i] # return return max_num
maximum-swap
[Py/Py3] A bit slower but simple solution w/ comments
ssshukla26
1
153
maximum swap
670
0.479
Medium
11,141
https://leetcode.com/problems/maximum-swap/discuss/1419957/Simple-Python-Beats-95
class Solution: def maximumSwap(self, num: int) -> int: s = str(num) iss = {n:i for i, n in enumerate(s)} heap = [-int(x) for x in s] heapq.heapify(heap) idx = 0 while idx < len(s) and heap: if int(s[idx]) < -heap[0]: res = [x for x in s] res[idx], res[iss[str(-heap[0])]] = res[iss[str(-heap[0])]], res[idx] return int(''.join([x for x in res])) elif int(s[idx]) == -heap[0]: heapq.heappop(heap) idx += 1 return num
maximum-swap
Simple Python Beats 95%
Pythagoras_the_3rd
1
443
maximum swap
670
0.479
Medium
11,142
https://leetcode.com/problems/maximum-swap/discuss/1419957/Simple-Python-Beats-95
class Solution: def maximumSwap(self, num: int) -> int: s = str(num) iss = {n:i for i, n in enumerate(s)} q = collections.deque(sorted([int(x) for x in s], key = lambda x:-x)) idx = 0 while idx < len(s) and q: if int(s[idx]) < q[0]: res = [x for x in s] res[idx], res[iss[str(q[0])]] = res[iss[str(q[0])]], res[idx] return int(''.join([x for x in res])) elif int(s[idx]) == heap[0]: q.popleft() idx += 1 return num
maximum-swap
Simple Python Beats 95%
Pythagoras_the_3rd
1
443
maximum swap
670
0.479
Medium
11,143
https://leetcode.com/problems/maximum-swap/discuss/2808082/using-hashmap
class Solution: def maximumSwap(self, num: int) -> int: # O(N), O(N) """ 2736 -> 7236 9973 -> 9973 9978 -> 9987 # { 2 : 0, 7 : 1, 3 : 2, 6 : 3} # { 9 : 1, 7 : 2, 8 : 3} """ # this num will convert into list [2, 7, 3, 6] num = list(map(int, str(num))) hashmap = {val : index for index, val in enumerate(num)} for index, val in enumerate(num): for searchval in range(9, val, -1): if searchval in hashmap and hashmap[searchval] > index: # swap num[index], num[hashmap[searchval]] = num[hashmap[searchval]], num[index] return int("".join(map(str, num))) return int("".join(map(str, num)))
maximum-swap
using hashmap
sahilkumar158
0
7
maximum swap
670
0.479
Medium
11,144
https://leetcode.com/problems/maximum-swap/discuss/2678671/Python3-Easy-O(N)-Solution
class Solution: def maximumSwap(self, num: int) -> int: num_arr = list(str(num)) # array with the number elements: 2736 -> ['2','7','3','6'] hashmap = {} # dictionary to store the elements of num and their indices for index, number in enumerate(num_arr): # O(N) hashmap[number] = index for i in range(0, len(num_arr)): # rotate over all elements of num_arr max_number = max(num_arr[i:]) # maximum number of num_arr starting at index i index_max_number = hashmap[max_number] # index of the maximum number if num_arr[i] < num_arr[index_max_number]: num_arr[i], num_arr[index_max_number] = num_arr[index_max_number], num_arr[i] break return int("".join(num_arr))
maximum-swap
Python3 Easy O(N) Solution
ramyh
0
26
maximum swap
670
0.479
Medium
11,145
https://leetcode.com/problems/maximum-swap/discuss/2666297/8-Line-Simple-Python-Solution
class Solution: def maximumSwap(self, num: int) -> int: pre, after, maxs, string = -1, -1, 0, str(num)[::-1] for index, char in enumerate(string): if int(char) > int(string[maxs]): maxs = index if int(char) < int(string[maxs]): pre, after = maxs, index return int(string[::-1]) if pre < 0 else int((string[:pre]+string[after]+string[pre+1:after]+string[pre]+string[after+1:])[::-1])
maximum-swap
8-Line Simple Python Solution
ParkerMW
0
10
maximum swap
670
0.479
Medium
11,146
https://leetcode.com/problems/maximum-swap/discuss/2509210/Python-easy-to-read-and-understand-or-greedy
class Solution: def maximumSwap(self, num: int) -> int: nums = list(str(num)) n = len(nums) suff = [0]*n suff[n-1] = int(nums[n-1]) d = {} for i, num in enumerate(nums): d[int(num)] = i for i in range(n-2, -1, -1): suff[i] = max(suff[i+1], int(nums[i])) for i in range(n): if int(nums[i]) < suff[i]: nums[i], nums[d[suff[i]]] = nums[d[suff[i]]], nums[i] break return int(''.join(nums))
maximum-swap
Python easy to read and understand | greedy
sanial2001
0
105
maximum swap
670
0.479
Medium
11,147
https://leetcode.com/problems/maximum-swap/discuss/2252541/Elegant-Solution
class Solution: def maximumSwap(self, num: int) -> int: s = str(num) total = [] for i in range(len(s)): for j in range(i+1,len(s)): num1 = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:] num2 = int(num1) if num2 > num: num = num2 return num``
maximum-swap
Elegant Solution
nth19912000
0
63
maximum swap
670
0.479
Medium
11,148
https://leetcode.com/problems/maximum-swap/discuss/1937752/Python3-92.42-or-Greedy-and-Recursion-or-Easy-Implementation
class Solution: def maximumSwap(self, num: int) -> int: n_l = list(str(num)) n_l = list(map(int, n_l)) ans = [] def process(n_l=n_l): nonlocal ans if len(n_l) == 1: ans.append(n_l[0]) return m_v = max(n_l) if n_l[0] == m_v: ans.append(n_l[0]) process(n_l[1:]) else: cur_max = (-math.inf, -1) i = 1 while i < len(n_l): if n_l[i] >= cur_max[0]: cur_max = n_l[i], i i += 1 n_l[0], n_l[cur_max[1]] = cur_max[0], n_l[0] ans += n_l return process() ans = list(map(str, ans)) return int(''.join(ans))
maximum-swap
Python3 92.42% | Greedy & Recursion | Easy Implementation
doneowth
0
160
maximum swap
670
0.479
Medium
11,149
https://leetcode.com/problems/maximum-swap/discuss/1885891/Python-Rolling-Max-Solution
class Solution: def maximumSwap(self, num: int) -> int: ans = [] origin = num res = num while num != 0: res = num % 10 ans.append(res) num //= 10 running_max = [] anchor_points = [] for index, a in enumerate(ans): if not running_max: running_max.append([index, a]) else: if running_max[-1][1] > a: anchor_points.append([index, running_max[-1][0]]) elif running_max[-1][1] == a: pass else: running_max.pop() running_max.append([index, a]) if not anchor_points: return origin else: new_ans = 0 index1, index2 = anchor_points[-1][0], anchor_points[-1][1] ans[index1], ans[index2] = ans[index2], ans[index1] for i in range(len(ans)): new_ans += ans[i] * 10 ** i return new_ans
maximum-swap
Python Rolling Max Solution
Vayne1994
0
208
maximum swap
670
0.479
Medium
11,150
https://leetcode.com/problems/maximum-swap/discuss/1826233/Python-3-with-comments
class Solution: def maximumSwap(self, num: int) -> int: num=list(str(num)) mx='-1' mi=0 #find the largest number once the subsequent numbers start increasing for i in range(1,len(num)): if num[i]>num[i-1]: if num[i]>mx: mx=num[i] #mi=i # find the right most occurance of the largest number which is out of order for i in range(len(num)): if num[i]==mx: mi=i #replace for i in range(len(num)): cr=num[i] if num[i]<mx: num[mi],num[i]=cr,mx break return int(''.join(num))
maximum-swap
Python 3 with comments
nabeelar
0
204
maximum swap
670
0.479
Medium
11,151
https://leetcode.com/problems/maximum-swap/discuss/1657371/the-easiest-to-understand-so-far(i-guess)-python
class Solution: def maximumSwap(self, num: int) -> int: nums = list(int(c) for c in str(num)) Sorted = sorted(nums, reverse = True) i, j = 0, 0 while i < len(nums): if Sorted[i] > nums[i]: # if find the first char bigger than original one, then swap these two val # give the curr nums[i] to a temp val to memorize the value tmp = nums[i] #change the original one to the bigger val nums[i] = Sorted[i] # why start from the right side and loop back untill the i, because before i there's no char bigger than the sorted array # nums: 1993 # sorted: 9931 # change the 1 in nums: 9 and find the right most 9 in (993) for j in range(len(nums)-1, i - 1, -1): if nums[j] == Sorted[i]: nums[j] = tmp return "".join([str(c) for c in nums]) i += 1 return num
maximum-swap
the easiest to understand so far(i guess) python
barry0828
0
242
maximum swap
670
0.479
Medium
11,152
https://leetcode.com/problems/maximum-swap/discuss/1494701/Python3-stack
class Solution: def maximumSwap(self, num: int) -> int: str_num = list(str(num)) stack = [] l = sys.maxsize for i in range(len(str_num)): while stack and str_num[stack[-1]] < str_num[i]: l = min(stack.pop(), l) stack.append(i) if l == sys.maxsize: return num r = l for s in stack: if s >= l and str_num[r] <= str_num[s]: r = s str_num[l], str_num[r] = str_num[r], str_num[l] return int("".join(str_num))
maximum-swap
Python3 stack
BichengWang
0
205
maximum swap
670
0.479
Medium
11,153
https://leetcode.com/problems/maximum-swap/discuss/1385807/Python-or-Simple-and-Easy-Solution
class Solution: def maximumSwap(self, num: int) -> int: numa=[] s=str(num) for i in s: numa.append(int(i)) samp=numa[:] numa.sort(reverse=True) ind=0 for i in range(len(s)): if samp[i]!=numa[i]: ind=i break mind=0 for i in range(len(s)-1,-1,-1): if samp[i]==numa[ind]: mind=i break samp[ind],samp[mind]=samp[mind],samp[ind] ans='' for i in samp: ans+=str(i) return int(ans) ```
maximum-swap
Python | Simple and Easy Solution
Hemanth1720
0
244
maximum swap
670
0.479
Medium
11,154
https://leetcode.com/problems/maximum-swap/discuss/1385285/Python-or-Easy-Solution
class Solution(object): def maximumSwap(self, num): """ :type num: int :rtype: int """ a=str(num) l=list(a.strip()) print(l) p=l[:] p.sort(reverse=True) fl=0 ## looping in descending - if swap is possible then we will swap and break for u in p: if fl==-1: break ## finding the index of the element in real list from last mm=l[::-1].index(u) mm=len(l)-mm-1 ## checking for possibility of swap for j in range(len(l)): if j>=mm: break if l[j]<u: l[j],l[mm]=l[mm],l[j] fl=-1 break print(l) c=''.join(r for r in l) return c
maximum-swap
Python | Easy Solution
nmk0462
0
175
maximum swap
670
0.479
Medium
11,155
https://leetcode.com/problems/maximum-swap/discuss/1263041/Easy-to-understand-Python
class Solution: def maximumSwap(self, num: int) -> int: helper = [ [] for _ in range(10) ] num = str(num) for i, digit in enumerate(num): helper[int(digit)].append(i) index = 0 for i in range(9, -1, -1): for pos in helper[i]: if pos != index: pos = helper[i][-1] s = num[:index] + num[pos] + num[index+1:pos] + num[index] + num[pos+1:] return int(s) else: index += 1 return int(num)
maximum-swap
Easy to understand Python
1354924411
0
89
maximum swap
670
0.479
Medium
11,156
https://leetcode.com/problems/maximum-swap/discuss/1049005/Python-Easy-to-understand-with-Explanation
class Solution: def maximumSwap(self, num: int) -> int: x = list(map(int, list(str(num)))) n = len(x) # Stores GREATER OR EQUAL element than self # To current idx's right side greater_idx = [ i for i in range(n) ] for i in reversed(range(n-1)): # IMP: '<=' is very important because we want # the RIGHT MOST greater idx # Edge case: 1993 if x[greater_idx[i]] <= x[greater_idx[i+1]]: greater_idx[i] = greater_idx[i+1] # print(greater_idx) for i in range(n): # IMP: 'x[greater_idx[i]] == x[i]' we don't want to swap # If greater item is same as current value # Edge case: 98128 if greater_idx[i] == i or x[greater_idx[i]] == x[i]: continue x[i], x[greater_idx[i]] = x[greater_idx[i]], x[i] return ''.join(list(map(str, x))) return ''.join(list(map(str, x)))
maximum-swap
Python, Easy to understand with Explanation
Raj214
0
113
maximum swap
670
0.479
Medium
11,157
https://leetcode.com/problems/maximum-swap/discuss/1006889/Linear-python-solution-with-short-explanation
class Solution: def maximumSwap(self, num: int) -> int: ''' Find earliest digit that has a higher digit come after it. Swap those two. dp[i] = idx for highest number after idx i. ''' if num < 10: return num nums = [int(d) for d in str(num)] dp = [None for _ in nums] # dp[i] = idx for max(nums[i+1], nums[dp[i+1]]) dp[-2] = len(nums) - 1 for i in reversed(range(len(dp)-2)): if nums[i+1] > nums[dp[i+1]]: dp[i] = i+1 else: dp[i] = dp[i+1] for i in range(len(nums)-1): swap = dp[i] if nums[swap] > nums[i]: nums[i], nums[swap] = nums[swap], nums[i] return int(''.join([str(d) for d in nums])) return num
maximum-swap
Linear python solution with short explanation
gins1
0
160
maximum swap
670
0.479
Medium
11,158
https://leetcode.com/problems/maximum-swap/discuss/895899/Python3-linear-scan-O(N)
class Solution: def maximumSwap(self, num: int) -> int: nums = list(map(int, str(num))) # array of digits ii = m = mm = None for i in reversed(range(len(nums))): if not m or nums[m] < nums[i]: m = i # max digit if nums[i] < nums[m]: ii, mm = i, m if mm: nums[ii], nums[mm] = nums[mm], nums[ii] return int("".join(map(str, nums)))
maximum-swap
[Python3] linear scan O(N)
ye15
0
94
maximum swap
670
0.479
Medium
11,159
https://leetcode.com/problems/maximum-swap/discuss/401798/Python-beats-70-simple-and-concise
class Solution: def maximumSwap(self, num: int) -> int: n = [int(x) for x in list(str(num))] m = [] for i in range(len(n)): if max(n[i:])!=n[i]: t = n[i:][::-1] ind = len(t) - t.index(max(t)) -1 n[i], n[i+ind] = n[i+ind], n[i] return ''.join([str(x) for x in n]) return num
maximum-swap
Python beats 70% `simple and concise
saffi
0
292
maximum swap
670
0.479
Medium
11,160
https://leetcode.com/problems/maximum-swap/discuss/1689186/Python-or-Simple-and-Easy
class Solution: def maximumSwap(self, num: int) -> int: num = str(num) for i in range(len(num)): max_number = max([k for k in num[i:]]) index = max([k for k in range(i, len(num)) if num[k]==max_number]) if int(num[i])<int(max_number): # String does not support item assignment, so using slicing for swapping the elements. num = num[:i] + num[index] + num[i+1:index] + num[i] + num[index+1:] break return int(num)
maximum-swap
Python | Simple and Easy
Aman_24
-2
333
maximum swap
670
0.479
Medium
11,161
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/405721/Beats-100-Python-Solution
class Solution: def findSecondMinimumValue(self, root: TreeNode) -> int: def inorderTraversal(root): if not root: return [] else: return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right) r = set(inorderTraversal(root)) if len(r)>=2: return sorted(list(r))[1] else: return -1
second-minimum-node-in-a-binary-tree
Beats 100% Python Solution
saffi
2
424
second minimum node in a binary tree
671
0.44
Easy
11,162
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/2525527/Simple-easy-to-understand-solution-for-python-beginners
class Solution: def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int: if not root: return None r, l = [root], [] while r: n = r.pop(0) l.append(n.val) if n.right: r.append(n.right) if n.left: r.append(n.left) l = sorted(list(set(l))) if len(l) == 1: return -1 return l[1]
second-minimum-node-in-a-binary-tree
Simple easy to understand solution for python beginners
pro6igy
0
18
second minimum node in a binary tree
671
0.44
Easy
11,163
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/1912418/Python3-Step-By-Step-Recursive-Solution-Faster-Than-86.87
class Solution: def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int: v = [] def dfs(tree): if not tree: return v.append(tree.val) dfs(tree.left) dfs(tree.right) dfs(root) nodes = [] for node in v: if node not in nodes: nodes.append(node) if len(nodes) == 1: return -1 return sorted(nodes)[1]
second-minimum-node-in-a-binary-tree
Python3, Step By Step Recursive Solution, Faster Than 86.87%
Hejita
0
28
second minimum node in a binary tree
671
0.44
Easy
11,164
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/1739890/Super-Easy-Solution-(Beats-100)-O(N)
class Solution: def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int: stack = [root] my_set = set() while len(stack) > 0: node = stack.pop() my_set.add(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) if len(my_set) == 1: return -1 # Remove the first minimum element my_set.remove(min(my_set)) # Return the second minimum element return min(my_set)
second-minimum-node-in-a-binary-tree
Super Easy Solution (Beats 100%) O(N)
flanqueue
0
83
second minimum node in a binary tree
671
0.44
Easy
11,165
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/1172632/WEEB-DOES-PYTHON-BFS
class Solution: def findSecondMinimumValue(self, root: TreeNode) -> int: queue, result = deque([root]), [] while queue: curNode = queue.popleft() result.append(curNode.val) if curNode.left: queue.append(curNode.left) if curNode.right: queue.append(curNode.right) result.sort() if result[-1] == result[0]: return -1 else: for i in range(len(result)-1): if result[i] < result[i+1]: return result[i+1]
second-minimum-node-in-a-binary-tree
WEEB DOES PYTHON BFS
Skywalker5423
0
79
second minimum node in a binary tree
671
0.44
Easy
11,166
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/1097041/Python-recursion-beats-80
class Solution: def findSecondMinimumValue(self, root: TreeNode) -> int: if not root.left: return -1 if not root: return -1 left=self.findSecondMinimumValue(root.left) right = self.findSecondMinimumValue(root.right) if root.right.val>root.val: if left==-1: return root.right.val else: return min(left,root.right.val) elif root.left.val>root.val: if right==-1: return root.left.val else: return min(right,root.left.val) else: if left==-1: return right if right==-1: return left return min(left, right)
second-minimum-node-in-a-binary-tree
Python recursion, beats 80%
kyswn
0
119
second minimum node in a binary tree
671
0.44
Easy
11,167
https://leetcode.com/problems/bulb-switcher-ii/discuss/897976/Python3-O(1)
class Solution: def flipLights(self, n: int, m: int) -> int: def fn(n, m): """Return number of different status.""" if m * n == 0: return 1 return fn(n-1, m-1) + fn(n-1, m) return fn(min(n, 3), min(m, 3))
bulb-switcher-ii
[Python3] O(1)
ye15
4
462
bulb switcher ii
672
0.51
Medium
11,168
https://leetcode.com/problems/bulb-switcher-ii/discuss/1535818/Python-3-or-Math-O(1)
class Solution: def flipLights(self, n: int, presses: int) -> int: if not presses: return 1 elif n < 3: if n == 1: return 2 elif presses >= 2: return 4 else: return 3 else: if presses >= 3: return 8 elif presses == 2: return 7 else: return 4
bulb-switcher-ii
Python 3 | Math, O(1)
idontknoooo
1
400
bulb switcher ii
672
0.51
Medium
11,169
https://leetcode.com/problems/bulb-switcher-ii/discuss/699368/Python3-bit-manipulate-first-3-bits-Bulb-Switcher-II
class Solution: # Operations: O(flip odds), E(flip evens), A(flip all), T(flip 3k + 1), N(flip nothing) states = { 'N': 0b000, 'A': 0b111, 'O': 0b101, 'E': 0b010, 'T': 0b001, 'AT': 0b111 ^ 0b001, 'OT': 0b101 ^ 0b001, 'ET': 0b010 ^ 0b001, } steps = { 0: ['N'], 1: ['A', 'O', 'E', 'T'], 2: ['N', 'A', 'O', 'E', 'AT', 'OT', 'ET'], 3: states.keys(), } def flipLights(self, n: int, m: int) -> int: n, m = min(n, 3), min(m, 3) mask = (1 << n) - 1 ans = set() for s in self.steps[m]: ans.add((0b111 ^ self.states[s]) &amp; mask) return len(ans)
bulb-switcher-ii
Python3 bit manipulate first 3 bits - Bulb Switcher II
r0bertz
1
313
bulb switcher ii
672
0.51
Medium
11,170
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/1881188/Python-DP-solution-explained
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: dp = [1] * len(nums) ct = [1] * len(nums) maxLen, maxCt = 0, 0 # same as the LIS code, iterate # over all the elements once and then # from 0 -> i again to compute LISs for i in range(len(nums)): for j in range(i): # If it's a valid LIS if nums[i] > nums[j]: # and if the length # of LIS at i wrt j # is going to be increased # update the length dp # and since this is just one # continous LIS, count of i # will become same as that of j if dp[j]+1 > dp[i]: dp[i] = dp[j] + 1 ct[i] = ct[j] # if on the other hand, the # length of the LIS at i becomes # the same as it was, it means # there's another LIS of this same # length, in this case, add the LIS # count of j to i, because the current # LIS count at i consists of ways to get # to this LIS from another path, and now # we're at a new path, so sum thse up # there's no point # in updating the length LIS here. elif dp[i] == dp[j] + 1: ct[i] += ct[j] # at any point, keep track # of the maxLen and maxCt # we'll use it to compute our result if dp[i] > maxLen: maxLen = dp[i] # now, we have the maxLength # of the given nums, we can iterate # over all 3 arrays (hypothetically) # and just add up the count of all those # LIS which are the longest (maxLen) # and that's the result for i in range(len(nums)): if maxLen == dp[i]: maxCt += ct[i] return maxCt
number-of-longest-increasing-subsequence
[Python] DP solution explained
buccatini
2
182
number of longest increasing subsequence
673
0.423
Medium
11,171
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/2800806/Python-(Simple-Dynamic-Programming)
class Solution: def findNumberOfLIS(self, nums): n = len(nums) dp, cnt, max_val = [1]*n, [1]*n, 1 for i in range(1,n): for j in range(i): if nums[i] > nums[j]: if dp[j] + 1 > dp[i]: dp[i], cnt[i] = 1 + dp[j], cnt[j] elif dp[j] + 1 == dp[i]: cnt[i] += cnt[j] max_val = max(max_val,dp[i]) return sum([j for i,j in zip(dp,cnt) if i == max_val])
number-of-longest-increasing-subsequence
Python (Simple Dynamic Programming)
rnotappl
0
4
number of longest increasing subsequence
673
0.423
Medium
11,172
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/2775249/n2-Complexity-Easy-to-Understand
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: longestDict = {} max_len = 1 max_cnt = 1 total_cnt = 0 for i in range(len(nums)): # length of LIS and count of LIS longestDict[i] = [1, 1] for i in range(len(nums)-1,-1,-1): for j in range(i+1, len(nums)): if nums[i] < nums[j]: # found another instance of present LIS length if longestDict[i][0] == longestDict[j][0] + 1: # increase the LIS count at i's position longestDict[i][1] += longestDict[j][1] # check if length of LIS could be more than current elif longestDict[i][0] < longestDict[j][0] + 1: # update length longestDict[i][0] = longestDict[j][0] + 1 # since length increased update count to j's count longestDict[i][1] = longestDict[j][1] max_len = max(longestDict[i][0], max_len) for LIS_size, LIS_count in longestDict.values(): if LIS_size == max_len: total_cnt += LIS_count return total_cnt
number-of-longest-increasing-subsequence
n^2 Complexity - Easy to Understand
shubhamsasane
0
4
number of longest increasing subsequence
673
0.423
Medium
11,173
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/2402159/Python-DP-Solution
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: n = len(nums) dp = [1 for _ in range(n)] freq = [1 for _ in range(n)] for i in range(n): for j in range(i): if nums[j] < nums[i] and 1 + dp[j] >= dp[i]: if dp[i] == 1 + dp[j]: freq[i] += freq[j] else: freq[i] = freq[j] dp[i] = 1 + dp[j] maximal = max(dp) res = 0 for idx, num in enumerate(dp): if num == maximal: res += freq[idx] return res
number-of-longest-increasing-subsequence
Python DP Solution
gouthampoloth
0
65
number of longest increasing subsequence
673
0.423
Medium
11,174
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/2317167/Python3-Solution-with-using-dp
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: dp = [0] * len(nums) # longest subseq cdp = [0] * len(nums) # count of longest subseq longest = 1 for i in range(len(nums)): dp[i] = 1 cdp[i] = 1 for j in range(i): if nums[i] > nums[j]: if dp[i] < dp[j] + 1: # found new longest seq dp[i] = dp[j] + 1 # update seq len for cur idx cdp[i] = cdp[j] # update count of longest seq (same as prev longest count seq because we only update len, for every prev longest can add one digit => general count longest seq are not change) elif dp[i] == dp[j] + 1: # found new way to achieve longest seq cdp[i] += cdp[j] # increase general count longest seq longest = max(longest, dp[i]) res = 0 for idx in range(len(dp)): # finally sum all count of longest seqs if dp[idx] == longest: res += cdp[idx] return res
number-of-longest-increasing-subsequence
[Python3] Solution with using dp
maosipov11
0
32
number of longest increasing subsequence
673
0.423
Medium
11,175
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/2297652/simple-python-dp
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: if not nums: return 0 n = len(nums) m, dp, cnt = 0, [1] * n, [1] * n for i in range(n): for j in range(i): if nums[j] < nums[i]: if dp[i] < dp[j]+1: dp[i], cnt[i] = dp[j]+1, cnt[j] elif dp[i] == dp[j]+1: cnt[i] += cnt[j] m = max(m, dp[i]) return sum(c for l, c in zip(dp, cnt) if l == m)
number-of-longest-increasing-subsequence
simple python dp
gasohel336
0
84
number of longest increasing subsequence
673
0.423
Medium
11,176
https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/896111/Python3-bottom-up-dp-O(N2)
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: lis = [[1, 1] for _ in nums] # longest increasing subsequence (length &amp; count) for i, x in enumerate(nums): for ii in range(i): if nums[ii] < x: if lis[ii][0] + 1 > lis[i][0]: lis[i] = [1 + lis[ii][0], lis[ii][1]] elif lis[ii][0] + 1 == lis[i][0]: lis[i][1] += lis[ii][1] mx, _ = max(lis, default=(0, 0)) return sum(y for x, y in lis if x == mx)
number-of-longest-increasing-subsequence
[Python3] bottom-up dp O(N^2)
ye15
0
91
number of longest increasing subsequence
673
0.423
Medium
11,177
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2445685/Two-python-solutions-using-dp-and-a-straightforward-soln
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: counter=1 temp=1 for i in range(0,len(nums)-1): if nums[i]<nums[i+1]: temp+=1 if temp>counter: counter=temp else: temp=1 return counter
longest-continuous-increasing-subsequence
Two python solutions using dp and a straightforward soln
guneet100
3
182
longest continuous increasing subsequence
674
0.491
Easy
11,178
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2053719/O(N)-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: maxLen = count = 1 for i in range(len(nums) - 1): if nums[i] < nums[i + 1]: count += 1 else: count = 1 maxLen = max(count, maxLen) return maxLen
longest-continuous-increasing-subsequence
O(N) solution
andrewnerdimo
2
54
longest continuous increasing subsequence
674
0.491
Easy
11,179
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1470624/Python3-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: msf = 0 # maxim so far meh = 1 # maxim ending here n = len(nums) if n == 1: return 1 last = nums[0] for i in range(1, n): if nums[i] > last: last = nums[i] meh += 1 else: meh = 1 last = nums[i] if msf < meh: msf = meh return msf
longest-continuous-increasing-subsequence
Python3 solution
FlorinnC1
1
174
longest continuous increasing subsequence
674
0.491
Easy
11,180
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1469705/python3-stack-fast-easy-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: stack = [nums[0]] ret = 1 for i in range(1, len(nums)): if stack and stack[-1] >= nums[i]: stack.clear() stack.append(nums[i]) ret = max(ret, len(stack)) return ret
longest-continuous-increasing-subsequence
python3 stack fast easy solution
BichengWang
1
93
longest continuous increasing subsequence
674
0.491
Easy
11,181
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2787076/Python-longest-continuous-increasing-subsequence.
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: if len(nums) == 1: return 1 longest = 0 starting, ending = 0, 0 for i in range(len(nums)-1): if nums[i] < nums[i+1]: ending += 1 else: ending += 1 longest = max(longest, (ending-starting)) starting = ending ending += 1 longest = max(longest, (ending-starting)) return longest
longest-continuous-increasing-subsequence
Python longest continuous increasing subsequence.
said_codes
0
3
longest continuous increasing subsequence
674
0.491
Easy
11,182
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2749857/Easy-Python-Solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: count = 1 ans = 1 for i in range(1,len(nums)): if nums[i] > nums[i-1]: count += 1 ans = max(ans,count) if nums[i] <= nums[i-1]: count = 1 return ans
longest-continuous-increasing-subsequence
Easy Python Solution
imkprakash
0
2
longest continuous increasing subsequence
674
0.491
Easy
11,183
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2749221/Is-my-solution-slow
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: ans = -math.inf i,j = 0,1 cnt = 1 if len(nums) == 1: return 1 while i in range(len(nums)) and j in range(len(nums)): if nums[j] > nums[i]: cnt+=1 else: cnt = 1 i+=1 j+=1 if cnt > ans: ans = cnt return ans
longest-continuous-increasing-subsequence
Is my solution slow
narutoright152
0
2
longest continuous increasing subsequence
674
0.491
Easy
11,184
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2650953/Easy-and-Faster-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: md=[1] dx=1 for i in range(1,len(nums)): if(nums[i]>nums[i-1]): dx+=1 else: md.append(dx) dx=1 md.append(dx) return max(md)
longest-continuous-increasing-subsequence
Easy and Faster solution
Raghunath_Reddy
0
1
longest continuous increasing subsequence
674
0.491
Easy
11,185
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2476144/Two-pointers-approach-98.72-memory-efficient-and-97.86-faster-in-Python
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: l, r = 0, 1 res = 0 ct = 1 while r < len(nums): if nums[l] < nums[r]: ct += 1 l += 1 r += 1 else: ct = 1 l = r r += 1 res = max(res, ct) res = max(res, ct) return res
longest-continuous-increasing-subsequence
Two pointers approach 98.72 % memory efficient and 97.86 % faster in Python
ankurbhambri
0
35
longest continuous increasing subsequence
674
0.491
Easy
11,186
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2311566/Easy-Python-Solution-or-O(n2)-or-O(n)-or-Sliding-Window
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: count=0 for i in range(len(nums)): a=nums[i] c=1 for j in range(i+1, len(nums)): if nums[j]>a: a=nums[j] c+=1 else: break count=max(count, c) return count
longest-continuous-increasing-subsequence
Easy Python Solution | O(n2) | O(n) | Sliding Window
Siddharth_singh
0
49
longest continuous increasing subsequence
674
0.491
Easy
11,187
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2311566/Easy-Python-Solution-or-O(n2)-or-O(n)-or-Sliding-Window
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: max_overall, max_current=0, 1 a=nums[0] for i in range(1, len(nums)): if nums[i]>a: a=nums[i] max_current+=1 else: a=nums[i] max_overall=max(max_overall, max_current) max_current=1 max_overall=max(max_overall, max_current) return max_overall
longest-continuous-increasing-subsequence
Easy Python Solution | O(n2) | O(n) | Sliding Window
Siddharth_singh
0
49
longest continuous increasing subsequence
674
0.491
Easy
11,188
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2060203/Python-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: ans = [] subs = 0 last = -10**9-1 for i in nums: if i > last: subs += 1 last = i else: ans += [subs] subs = 1 last = i ans += [subs] return max(ans)
longest-continuous-increasing-subsequence
Python solution
StikS32
0
58
longest continuous increasing subsequence
674
0.491
Easy
11,189
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1950369/Python-easy-solution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: dp=[0]*len(nums);dp[0]=1;i=1 while i!=len(nums): if nums[i-1]<nums[i]: dp[i]=dp[i-1]+1 elif nums[i-1]>=nums[i]: dp[i]=1 i+=1 return max(dp)
longest-continuous-increasing-subsequence
Python easy solution
Whitedevil07
0
43
longest continuous increasing subsequence
674
0.491
Easy
11,190
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1847738/PYTHON-ONE-PASS-solution-step-by-step-(76ms)
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: #Get the length LENGTH = len ( nums ); #Keep track of the max and the current streak maxStreak = 1; streak = 1; #Point at the first index pointer = 1; #Because previous starts out at the zeroth index prev = nums[ 0 ]; while pointer < LENGTH: #Use the pointer to get the current value current = nums[ pointer ]; #Check the current against the previous value if current > prev: streak += 1; else: streak = 1; #Update the streak maxStreak = max( streak, maxStreak ); #Update the previous to current and increment the pointer prev = current; pointer += 1; #Return the max return maxStreak;
longest-continuous-increasing-subsequence
PYTHON ONE PASS solution step-by-step (76ms)
greg_savage
0
62
longest continuous increasing subsequence
674
0.491
Easy
11,191
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1833571/7-Lines-Python-Solution-oror-92-Faster-oror-Memory-less-than-87
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: cnt=1 ; ans=0 for i in range(len(nums)-1): if nums[i+1]<=nums[i]: if cnt>ans: ans=cnt cnt=0 cnt+=1 return max(cnt,ans)
longest-continuous-increasing-subsequence
7-Lines Python Solution || 92% Faster || Memory less than 87%
Taha-C
0
67
longest continuous increasing subsequence
674
0.491
Easy
11,192
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1520680/One-pass-96-speed
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: count = max_count = 1 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: count += 1 else: max_count = max(max_count, count) count = 1 return max(max_count, count)
longest-continuous-increasing-subsequence
One pass, 96% speed
EvgenySH
0
122
longest continuous increasing subsequence
674
0.491
Easy
11,193
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1414053/Python-oror-Simple-and-Easy-Approach
class Solution: def findLengthOfLCIS(self, lst: List[int]) -> int: temp = lst[0] maxi = 1 count = 1 for i in range(1, len(lst)): if temp < lst[i]: count += 1 else: count = 1 temp = lst[i] if count > maxi: maxi = count return (maxi)
longest-continuous-increasing-subsequence
Python || Simple and Easy Approach
naveenrathore
0
73
longest continuous increasing subsequence
674
0.491
Easy
11,194
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1374179/Simple-Python-solution-space%3AO(1)-Time%3AO(N)
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: longest = 1 continuous_long = 1 # considered first element for i in range(1,len(nums)): if nums[i-1]<nums[i]: # chained to continuous continuous_long+=1 else: # break the chain. # Compare previous longest and save the best. longest = max(continuous_long, longest) # Reset continuous long continuous_long = 1 # Consideration of last chain unbroken but ended by array length longest = max(longest, continuous_long) return longest
longest-continuous-increasing-subsequence
Simple Python solution space:O(1) Time:O(N)
SathvikPN
0
42
longest continuous increasing subsequence
674
0.491
Easy
11,195
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1238617/Python3-simple-solution-beats-90-users
class Solution: def findLengthOfLCIS(self, nums): z = 1 res = 1 for i in range(1,len(nums)): if nums[i-1] < nums[i]: z += 1 if i == len(nums)-1: res = max(res,z) else: res = max(res, z) z = 1 return res
longest-continuous-increasing-subsequence
Python3 simple solution beats 90% users
EklavyaJoshi
0
42
longest continuous increasing subsequence
674
0.491
Easy
11,196
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/352926/Solution-in-Python-3-(beats-100)-(-O(n)-time-)-(-O(1)-space-)
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: L, M, s = len(nums), 0, 0 if L == 0: return 0 for i in range(L-1): s += 1 if nums[i+1] <= nums[i]: if s > M: M = s s = 0 return max(M,s+1) - Junaid Mansuri (LeetCode ID)@hotmail.com
longest-continuous-increasing-subsequence
Solution in Python 3 (beats 100%) ( O(n) time ) ( O(1) space )
junaidmansuri
0
170
longest continuous increasing subsequence
674
0.491
Easy
11,197
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1308581/Python3-dollarolution
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: mx, x = 0, 1 for i in range(1,len(nums)): if nums[i] > nums[i-1]: x += 1 else: if x > mx: mx = x x = 1 m = nums[i] if x > mx: mx = x return mx
longest-continuous-increasing-subsequence
Python3 $olution
AakRay
-1
29
longest continuous increasing subsequence
674
0.491
Easy
11,198
https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/1206337/Faster-than-93-solutions
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: curlen = 0 maxlen = 0 if not nums: return 0 for i in nums: if nums[i] < nums[i+1]: curlen +=1 maxlen = curlen return maxlen
longest-continuous-increasing-subsequence
Faster than 93% solutions
devanshsolani30
-2
67
longest continuous increasing subsequence
674
0.491
Easy
11,199