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/two-sum-iv-input-is-a-bst/discuss/2680760/C%2B%2BPython-4-Approaches-or100-Fast-or-Super-Clear-or | class Solution:
def helper(self,currNode,selectedNode,target):
if not currNode: #This helper function search second element from the remaining elements
return False
if((currNode != selectedNode) and (currNode.val == target)):
return True
if(target > currNode.val):#if target is greater than current element then we search in right subtree
return self.helper(currNode.right,selectedNode,target)
else:#if target is less than current element then we search in left subtree
return self.helper(currNode.left,selectedNode,target)
def solve(self,currNode,root,k):
if not currNode: #This function selects first element
return False
return self.helper(root,currNode,k-currNode.val) or self.solve(currNode.left,root,k) or self.solve(currNode.right,root,k)
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
return self.solve(root,root,k) | two-sum-iv-input-is-a-bst | [C++/Python] 4 Approaches |100% Fast | Super Clear |π₯π₯π₯ | ram_kishan1998 | 0 | 28 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,900 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680760/C%2B%2BPython-4-Approaches-or100-Fast-or-Super-Clear-or | class Solution:
def __init__(self):
self.st = set()
def solve(self,currNode,root,k):
if not currNode:
return False
if(k-currNode.val) in self.st:
return True
self.st.add(currNode.val)
return self.solve(currNode.left,root,k) or self.solve(currNode.right,root,k)
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
return self.solve(root,root,k) | two-sum-iv-input-is-a-bst | [C++/Python] 4 Approaches |100% Fast | Super Clear |π₯π₯π₯ | ram_kishan1998 | 0 | 28 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,901 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680760/C%2B%2BPython-4-Approaches-or100-Fast-or-Super-Clear-or | class Solution:
def __init__(self):
self.arr = []
def solve(self,currNode):
if not currNode:
return
self.solve(currNode.left)
self.arr.append(currNode.val)
self.solve(currNode.right)
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
self.solve(root)
i,j = 0, len(self.arr)-1
while i < j:
if(self.arr[i]+self.arr[j] == k):
return True
if(self.arr[i]+self.arr[j] > k):
j -= 1
else:
i += 1
return False | two-sum-iv-input-is-a-bst | [C++/Python] 4 Approaches |100% Fast | Super Clear |π₯π₯π₯ | ram_kishan1998 | 0 | 28 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,902 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680619/Unique-and-Easy-or-96-faster-or-speed-O(n)-and-memory-O(n) | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
res = []
dict = {}
def Inorder(root):
if not root:
return
Inorder(root.left)
res.append(root.val)
Inorder(root.right)
Inorder(root)
for index, ele in enumerate(res):
if k - ele in dict:
return True
dict[ele] = index
return False | two-sum-iv-input-is-a-bst | Unique and Easy | 96% faster | speed O(n) and memory O(n) | shivanand007 | 0 | 32 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,903 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680519/Python-(Faster-than-95)-or-Iterative-BFS-or-Recursive-DFS | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
if not root:
return False
check = set()
q = deque()
q.append(root)
while q:
for _ in range(len(q)):
node = q.popleft()
if node:
if node.val in check:
return True
check.add(k - node.val)
q.append(node.left)
q.append(node.right)
return False | two-sum-iv-input-is-a-bst | Python (Faster than 95%) | Iterative BFS | Recursive DFS | KevinJM17 | 0 | 4 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,904 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680519/Python-(Faster-than-95)-or-Iterative-BFS-or-Recursive-DFS | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
if not root:
return False
def dfs(node, check):
if node:
if node.val in check:
return True
check.add(k - node.val)
return dfs(node.left, check) or dfs(node.right, check)
return False
return dfs(root, set()) | two-sum-iv-input-is-a-bst | Python (Faster than 95%) | Iterative BFS | Recursive DFS | KevinJM17 | 0 | 4 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,905 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2679555/Python3-or-Tree-Traversal-%2B-Hash-Set | class Solution:
def recur(self, node):
if not node:
return
self.hashMap[node.val] = 1
self.recur(node.left)
self.recur(node.right)
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
self.hashMap = {}
self.recur(root)
for key in self.hashMap:
d = k - key
if d != key and d in self.hashMap:
return True
return False | two-sum-iv-input-is-a-bst | Python3 | Tree Traversal + Hash Set | vikinam97 | 0 | 2 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,906 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2679478/Simple-BFS | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
q=deque([root])
seen=set()
while q:
curr=q.popleft()
if k-curr.val in seen:
return True
seen.add(curr.val)
if curr.left:
q.append(curr.left)
if curr.right:
q.append(curr.right)
return False | two-sum-iv-input-is-a-bst | Simple BFS | immortal101 | 0 | 57 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,907 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2576129/9-Lines-Python-Beats-95.77-in-Runtime-95.58-in-Memory-Usage | class Solution(object):
def findTarget(self, root, k):
theSet = set()
stack = [root]
while stack:
node = stack.pop()
if node:
if node.val in theSet: return True
stack.append(node.right)
stack.append(node.left)
theSet.add(k - node.val) | two-sum-iv-input-is-a-bst | β
9-Lines Python, Beats 95.77% in Runtime, 95.58% in Memory Usage | HappyLunchJazz | 0 | 35 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,908 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2401163/Python-Accurate-Solution-using-Set-oror-Documented | class Solution:
# Time and Space are both O(n)
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
lookup = set() # set for searching with O(1) time
def dfs(root):
if root:
if k - root.val in lookup: # look for k - val,
return True # return True if found
lookup.add(root.val) # add the value into set
return dfs(root.left) or dfs(root.right) # look in children
return False # reached at leaf, return False
return dfs(root) # start DFS traversal from root | two-sum-iv-input-is-a-bst | [Python] Accurate Solution using Set || Documented | Buntynara | 0 | 20 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,909 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2387300/Easiest-Python-Solution-or-TC-Better-than-98 | class Solution:
def __init__(self):
self.d = {}
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
if not root:
return False
if root.val in self.d:
return True
else:
self.d[k - root.val] = 1
return self.findTarget(root.right, k) or self.findTarget(root.left, k) | two-sum-iv-input-is-a-bst | Easiest Python Solution | TC Better than 98% | Racernigga | 0 | 99 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,910 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2337051/Easy-peasy-Solution-in-Python-3-81ms | class Solution:
def __init__(self):
self.theSet = set()
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
if not root.left and not root.right: return False
stack = [root]
while stack:
node = stack.pop()
if node.val in self.theSet:
return True
self.theSet.add(k - node.val)
if node.left: stack.insert(0, node.left)
if node.right: stack.insert(0, node.right)
return False | two-sum-iv-input-is-a-bst | Easy-peasy Solution in Python 3, 81ms | HappyLunchJazz | 0 | 57 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,911 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1997482/Python3-Simple-solution | class Solution:
def findTarget(self, root, k):
if not root: return False
bfs, s = [root], set()
for i in bfs:
if k - i.val in s: return True
s.add(i.val)
if i.left: bfs.append(i.left)
if i.right: bfs.append(i.right)
return False | two-sum-iv-input-is-a-bst | Python3 Simple solution | nomanaasif9 | 0 | 121 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,912 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1920956/Python-DFS-%2B-Dictionary-With-Explanation | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
m, v = {}, []
def dfs(tree):
if not tree:
return
if tree.val in m:
m[tree.val] += 1
else:
m[tree.val] = 1
v.append(tree.val)
dfs(tree.left)
dfs(tree.right)
dfs(root)
for i in v:
res = k - i
if res == i:
if m[i] > 1:
return True
elif m.get(res):
return True
return False | two-sum-iv-input-is-a-bst | Python, DFS + Dictionary, With Explanation | Hejita | 0 | 66 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,913 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1814700/Python-Simple-Python-Solution-Using-Iterative-Approach | class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
self.array = []
def helper(node):
if node==None:
return None
helper(node.left)
self.array.append(node.val)
helper(node.right)
return self.array
helper(root)
for i in range(len(self.array)-1):
for j in range(i+1,len(self.array)):
if self.array[i] + self.array[j] == k:
return True
return False | two-sum-iv-input-is-a-bst | [ Python ] β
β
Simple Python Solution Using Iterative Approach π₯β | ASHOK_KUMAR_MEGHVANSHI | 0 | 124 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,914 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1511441/Easy-to-read-python-(BFS) | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
queue = []
seen = [] # k - vals (vals that we need to see in the tree)
it = 0 # to handle single root case
queue.append(root)
while(queue):
it += 1
currNode = queue.pop(0)
# if we saw currNode val in dict
if k-currNode.val in seen and it > 1:
return True
seen.append(currNode.val)
# BFS Calls
if currNode.left:
queue.append(currNode.left)
if currNode.right:
queue.append(currNode.right)
return False | two-sum-iv-input-is-a-bst | Easy to read python (BFS) | Adam-Makaoui | 0 | 153 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,915 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1422643/Recursive-until-a-pair-found-92-speed | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
ans = False
values = set()
def traverse(node: TreeNode) -> None:
nonlocal ans, values
if not ans:
if k - node.val in values:
ans = True
else:
values.add(node.val)
if node.left:
traverse(node.left)
if node.right:
traverse(node.right)
traverse(root)
return ans | two-sum-iv-input-is-a-bst | Recursive until a pair found, 92% speed | EvgenySH | 0 | 150 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,916 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1421734/Pythjon3-in-order-iterator | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
seen = set()
stack = [root]
while stack:
node = stack.pop()
if k - node.val in seen: return True
seen.add(node.val)
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return False | two-sum-iv-input-is-a-bst | [Pythjon3] in-order iterator | ye15 | 0 | 37 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,917 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1421734/Pythjon3-in-order-iterator | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
lo = hi = root
left, right = [], []
while lo:
left.append(lo)
lo = lo.left
lo = left.pop()
while hi:
right.append(hi)
hi = hi.right
hi = right.pop()
while lo.val < hi.val:
if lo.val + hi.val < k:
lo = lo.right
while lo:
left.append(lo)
lo = lo.left
lo = left.pop()
elif lo.val + hi.val == k: return True
else:
hi = hi.left
while hi:
right.append(hi)
hi = hi.right
hi = right.pop()
return False | two-sum-iv-input-is-a-bst | [Pythjon3] in-order iterator | ye15 | 0 | 37 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,918 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1421734/Pythjon3-in-order-iterator | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
def fn(node, tf):
if node:
yield from fn(node.left, tf) if tf else fn(node.right, tf)
yield node.val
yield from fn(node.right, tf) if tf else fn(node.left, tf)
fit = fn(root, 1) # forward iterator
bit = fn(root, 0) # backward iterator
lo, hi = next(fit), next(bit)
while lo < hi:
sm = lo + hi
if sm < k: lo = next(fit)
elif sm == k: return True
else: hi = next(bit)
return False | two-sum-iv-input-is-a-bst | [Pythjon3] in-order iterator | ye15 | 0 | 37 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,919 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1421555/Python3-Clean-post-order-dfs-solution-with-results | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
_set = set()
stack = collections.deque([])
last_visited = None
while stack or root:
if root != None:
stack.append(root)
root = root.left
else:
node = stack[-1]
if node.right and node.right != last_visited:
root = node.right
else:
last_visited = stack.pop()
if k - last_visited.val in _set:
return True
_set.add(last_visited.val)
return False | two-sum-iv-input-is-a-bst | [Python3] Clean post-order dfs solution with results | maosipov11 | 0 | 24 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,920 |
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1421396/Python3-Two-Sum-IV-A-pair-of-generators | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
#Generates node values depth-first from right-to-left
def dftRtoL(root):
if root.right: yield from dftRtoL(root.right)
yield root.val
if root.left: yield from dftRtoL(root.left)
#Generates node values depth-first from left-to-right
def dftLtoR(root):
if root.left: yield from dftLtoR(root.left)
yield root.val
if root.right: yield from dftLtoR(root.right)
pl, pr = dftLtoR(root), dftRtoL(root)
l, r = next(pl), next(pr)
#If the node values are equal then all nodes have been checked and there is no solution
while l != r:
#l+r is too small, decrease l
if l + r < k:
l = next(pl)
#l+r is too big, increase r
elif l + r > k:
r = next(pr)
#l+r == k, the solution is found
else: return True
return False | two-sum-iv-input-is-a-bst | [Python3] Two Sum IV, A pair of generators | vscala | 0 | 43 | two sum iv input is a bst | 653 | 0.61 | Easy | 10,921 |
https://leetcode.com/problems/maximum-binary-tree/discuss/944324/simple-python3-solution-with-recursion | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
# base case
if not nums:
return None
max_val = max(nums)
max_idx = nums.index(max_val)
root = TreeNode(max_val)
root.left = self.constructMaximumBinaryTree(nums[:max_idx])
root.right = self.constructMaximumBinaryTree(nums[max_idx+1:])
return root | maximum-binary-tree | simple python3 solution with recursion | Gushen88 | 2 | 100 | maximum binary tree | 654 | 0.845 | Medium | 10,922 |
https://leetcode.com/problems/maximum-binary-tree/discuss/894897/Python3-stack-O(N) | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums: return # boundary condition
i = nums.index(max(nums))
return TreeNode(nums[i], left=self.constructMaximumBinaryTree(nums[:i]), right=self.constructMaximumBinaryTree(nums[i+1:])) | maximum-binary-tree | [Python3] stack O(N) | ye15 | 2 | 141 | maximum binary tree | 654 | 0.845 | Medium | 10,923 |
https://leetcode.com/problems/maximum-binary-tree/discuss/894897/Python3-stack-O(N) | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
stack = []
for x in nums:
node = TreeNode(x)
while stack and stack[-1].val < x: node.left = stack.pop()
if stack: stack[-1].right = node
stack.append(node)
return stack[0] | maximum-binary-tree | [Python3] stack O(N) | ye15 | 2 | 141 | maximum binary tree | 654 | 0.845 | Medium | 10,924 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2492270/Easy-Recursive-Python-Accepted | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def traverse_tree(num: list):
if len(num):
max_number = max(num)
max_index = num.index(max_number)
left = num[0:max_index]
right = num[max_index+1:]
return TreeNode(val=max_number, left=traverse_tree(left), right=traverse_tree(right))
return traverse_tree(nums) | maximum-binary-tree | Easy Recursive Python - Accepted | cengleby86 | 0 | 9 | maximum binary tree | 654 | 0.845 | Medium | 10,925 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2455864/Python-Recursion-Simple-easy-to-understand-Recursive-solution | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
_max = max(nums)
_max_i = nums.index(_max)
root = TreeNode(_max)
root.left = self.constructMaximumBinaryTree(nums[:_max_i])
root.right = self.constructMaximumBinaryTree(nums[_max_i+1:])
return root | maximum-binary-tree | [Python] [Recursion] Simple, easy to understand Recursive solution | deucesevenallin | 0 | 31 | maximum binary tree | 654 | 0.845 | Medium | 10,926 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2400092/Python3-oror-recursion-oror-O(n) | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def buildTree(arr):
# if array is empty, return None (empty node)
if len(arr)==0:
return None
# find maximum value and its position
val, idx = max(arr), arr.index(max(arr))
# build a node with left and right node recursively
node = TreeNode(val, buildTree(arr[:idx]), buildTree(arr[idx+1:]))
return node
return buildTree(nums) | maximum-binary-tree | Python3 || recursion || O(n) | xmmm0 | 0 | 9 | maximum binary tree | 654 | 0.845 | Medium | 10,927 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2138623/Python-oror-Recursive-Straight-Forward | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums: return None
max_i, max_ = 0, 0
for i,v in enumerate(nums):
if v > max_ :
max_i, max_ = i, v
root = TreeNode(max_)
root.left = self.constructMaximumBinaryTree(nums[:max_i])
root.right = self.constructMaximumBinaryTree(nums[max_i + 1:])
return root | maximum-binary-tree | Python || Recursive Straight Forward | morpheusdurden | 0 | 20 | maximum binary tree | 654 | 0.845 | Medium | 10,928 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2084537/Python-Simple-Solution | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
max_el = max(nums)
max_el_idx = nums.index(max_el)
root = TreeNode(max_el)
# construct left Tree
root.left = self.constructMaximumBinaryTree(nums[:max_el_idx])
# construct right Tree
root.right = self.constructMaximumBinaryTree(nums[max_el_idx+1:])
return root
``` | maximum-binary-tree | Python Simple Solution | Nk0311 | 0 | 20 | maximum binary tree | 654 | 0.845 | Medium | 10,929 |
https://leetcode.com/problems/maximum-binary-tree/discuss/2038934/Python-3-example-with-Monotonic-Stack-approach | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
stack = []
for num in nums:
new_node = TreeNode(num)
right_child = None
while stack and stack[-1].val < num:
node = stack.pop()
node.right = right_child
right_child = node
new_node.left = right_child
stack.append(new_node)
root = None
while stack:
node = stack.pop()
node.right = root
root = node
return root | maximum-binary-tree | Python 3 example with Monotonic Stack approach | NonameDeadinside | 0 | 61 | maximum binary tree | 654 | 0.845 | Medium | 10,930 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1685742/Simple-Python3-solution | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
maxi,index = -1,-1
for i in range(len(nums)):
if maxi < nums[i]:
maxi = nums[i]
index = i
root = TreeNode(nums[index], None, None)
if len(nums) == 1:
return root
if index == 0:
root.left == None
root.right = self.constructMaximumBinaryTree(nums[1:])
elif index == len(nums)-1:
root.right = None
root.left = self.constructMaximumBinaryTree(nums[:-1])
else:
root.left = self.constructMaximumBinaryTree(nums[:index])
root.right = self.constructMaximumBinaryTree(nums[index+1:])
return root | maximum-binary-tree | Simple Python3 solution | devansh_raj | 0 | 28 | maximum binary tree | 654 | 0.845 | Medium | 10,931 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1681785/Python-Simple-recursive-DFS-explained | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
# since we're passing slice of our
# original nums, at one point, it's
# bound to be empty, return in that case
if len(nums) == 0: return
# get the max value in the array
# at this recursion level and also
# the index to further slice the array
max_val, idx = 0, 0
for i, v in enumerate(nums):
if v > max_val:
max_val, idx = v, i
root = TreeNode(max_val, None, None)
# recursively call the method to build
# the left and the right subtree
root.left = self.constructMaximumBinaryTree(nums[:idx])
root.right = self.constructMaximumBinaryTree(nums[idx+1:])
return root | maximum-binary-tree | [Python] Simple recursive DFS explained | buccatini | 0 | 38 | maximum binary tree | 654 | 0.845 | Medium | 10,932 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1608807/Clean-and-Easy-Recursion-in-Python | class Solution:
def recursiveTree(self, nums: List[int]) -> TreeNode:
# Get Split
split_max = max(nums)
split_idx = nums.index(split_max)
# Make Root
root = TreeNode(split_max)
# Prefix Recursion
prefix = nums[:split_idx]
if len(prefix) > 0:
root.left = self.recursiveTree(prefix)
# Suffix Recursion
suffix = nums[split_idx+1:]
if len(suffix) > 0:
root.right = self.recursiveTree(suffix)
return root
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
return self.recursiveTree(nums) | maximum-binary-tree | Clean & Easy Recursion in Python | dualslash | 0 | 87 | maximum binary tree | 654 | 0.845 | Medium | 10,933 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1538336/Python-intuitive-solution-(easy-to-understand) | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def helper(arr):
if arr:
v = max(arr)
idx = arr.index(v)
node = TreeNode(v)
node.left = helper(arr[:idx])
node.right = helper(arr[idx+1:])
return node
return helper(nums) | maximum-binary-tree | Python intuitive solution (easy to understand) | byuns9334 | 0 | 45 | maximum binary tree | 654 | 0.845 | Medium | 10,934 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1073247/Elegant-Python-Recursion | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if nums:
root = TreeNode(max(nums))
index = nums.index(max(nums))
root.left = self.constructMaximumBinaryTree(nums[:index])
root.right = self.constructMaximumBinaryTree(nums[index+1:])
return root | maximum-binary-tree | Elegant Python Recursion | 111989 | 0 | 59 | maximum binary tree | 654 | 0.845 | Medium | 10,935 |
https://leetcode.com/problems/maximum-binary-tree/discuss/1025454/Python3-simple-recursion | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if nums == []:
return None
else:
node = TreeNode(max(nums))
node.left = self.constructMaximumBinaryTree(nums[:nums.index(max(nums))])
node.right = self.constructMaximumBinaryTree(nums[nums.index(max(nums))+1:])
return node | maximum-binary-tree | Python3 simple recursion | EklavyaJoshi | 0 | 33 | maximum binary tree | 654 | 0.845 | Medium | 10,936 |
https://leetcode.com/problems/print-binary-tree/discuss/1384379/Python-3-or-DFS-%2B-BFS-(Level-order-traversal)-or-Explanation | class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
height = 0
def dfs(node, h): # Find height
nonlocal height
height = max(height, h)
if node.left:
dfs(node.left, h+1)
if node.right:
dfs(node.right, h+1)
dfs(root, 0)
n = 2 ** (height + 1) - 1 # Get `n`
offset = (n - 1) // 2 # Column for root node
ans = [[''] * n for _ in range(height + 1)]
q = [(root, 0, offset)]
for i in range(height+1): # BFS
tmp_q = []
while q:
cur, r, c = q.pop()
ans[r][c] = str(cur.val)
if cur.left:
tmp_q.append((cur.left, r+1, c-2 ** (height - r - 1)))
if cur.right:
tmp_q.append((cur.right, r+1, c+2 ** (height - r - 1)))
q = tmp_q
return ans | print-binary-tree | Python 3 | DFS + BFS (Level-order-traversal) | Explanation | idontknoooo | 2 | 256 | print binary tree | 655 | 0.614 | Medium | 10,937 |
https://leetcode.com/problems/print-binary-tree/discuss/1962656/python-3-oror-simple-recursive-solution | class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
height = self.height(root) - 1
m, n = height + 1, 2 ** (height + 1) - 1
res = [[''] * n for _ in range(m)]
def helper(root, r, c):
if root is None:
return
res[r][c] = str(root.val)
x = 2 ** (height - r - 1)
helper(root.left, r + 1, c - x)
helper(root.right, r + 1, c + x)
helper(root, 0, (n - 1) // 2)
return res
def height(self, root):
if root is None:
return 0
return 1 + max(self.height(root.left), self.height(root.right)) | print-binary-tree | python 3 || simple recursive solution | dereky4 | 1 | 122 | print binary tree | 655 | 0.614 | Medium | 10,938 |
https://leetcode.com/problems/print-binary-tree/discuss/1502626/Python3-solution | class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
def height(node,c):
if not node:
return c
return max(height(node.left,c+1),height(node.right,c+1))
self.height = height(root,-1)
m = self.height + 1
n = 2**(self.height+1)-1
self.mat = []
for i in range(m):
z = []
for j in range(n):
z.append("")
self.mat.append(z)
def make(node,row,col,mat,height):
if node:
if node.left:
mat[row+1][col-2**(height-row-1)] = str(node.left.val)
make(node.left,row+1,col-2**(height-row-1),mat,height)
if node.right:
mat[row+1][col+2**(height-row-1)] = str(node.right.val)
make(node.right,row+1,col+2**(height-row-1),mat,height)
self.mat[0][(n-1)//2] = str(root.val)
make(root,0,(n-1)//2,self.mat,self.height)
return self.mat | print-binary-tree | Python3 solution | EklavyaJoshi | 1 | 138 | print binary tree | 655 | 0.614 | Medium | 10,939 |
https://leetcode.com/problems/print-binary-tree/discuss/2722717/Python3-or-Recursive-or-Easy-Understanding-or-DFS-or-EASY | class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
# GET HEIGHT OF THE TREE
def dfs(node, count):
if not node: return count
return max(dfs(node.left, count+1), dfs(node.right, count+1))
height = dfs(root, -1)
# m and n IS PROVIDED FORMULA FROM PROBLEM DESCRIPTION
m = height + 1
n = (2 ** (m)) - 1
# CREATE RESULT
result = [["" for x in range(0, n)] for x in range(0, m)]
# r and c IS PROVIDED FORMULA FROM PROBLEM DESCRIPTION
r = 0
c = (n-1) // 2
# FILL THE RESULT WITH DFS TRAVERSAL
# lc and rc IS PROVIDED FORMULA FROM DESCRIPTION
def plot(node, r, c):
if not node: return
result[r][c] = str(node.val)
if node.left:
lc = c - (2 ** (height - r - 1))
plot(node.left, r+1, lc)
if node.right:
rc = c + (2 ** (height - r - 1))
plot(node.right, r+1, rc)
plot(root, r, c)
return result | print-binary-tree | Python3 | Recursive | Easy Understanding | DFS | EASY | weed_smoke | 0 | 9 | print binary tree | 655 | 0.614 | Medium | 10,940 |
https://leetcode.com/problems/print-binary-tree/discuss/1621633/BFS-Traversal-oror-O(N)-TIME-O(N)-SPACE-oror-greater-85-on-TIME-and-MEMORY | class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
@cache
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
root_height = height(root)
h = root_height #height
w = 2**(h)-1 #width
twoDArr = [[""]*w for _ in range(h)]
#BFS Traversal
stack = [[root, [0, (w-1)//2]]]
while stack:
next_queue = []
while len(stack) > 0:
cell = stack.pop()
node = cell[0]
[r,c] = cell[1]
twoDArr[r][c] = str(node.val)
if node.left:
next_queue.append([node.left, [r+1, c-2**(h-r-2)]])
if node.right:
next_queue.append([node.right, [r+1, c+2**(h-r-2)]])
stack = next_queue
return twoDArr | print-binary-tree | BFS Traversal || O(N) TIME, O(N) SPACE || > 85% on TIME & MEMORY | henriducard | 0 | 106 | print binary tree | 655 | 0.614 | Medium | 10,941 |
https://leetcode.com/problems/print-binary-tree/discuss/894989/Python3-dfs-(recursive) | class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
ht = lambda node: 1 + max(ht(node.left), ht(node.right)) if node else 0 # height of binary tree
m = ht(root) # rows
n = 2**m - 1 # columns
def dfs(node, i, lo=0, hi=n):
"""Populate ans via dfs."""
if not node: return
mid = lo + hi >> 1
ans[i][mid] = str(node.val)
dfs(node.left, i+1, lo, mid) or dfs(node.right, i+1, mid+1, hi)
ans = [[""]*n for _ in range(m)]
dfs(root, 0)
return ans | print-binary-tree | [Python3] dfs (recursive) | ye15 | 0 | 55 | print binary tree | 655 | 0.614 | Medium | 10,942 |
https://leetcode.com/problems/robot-return-to-origin/discuss/342078/Solution-in-Python-3-(~beats-99)-(-one-line-) | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
- Python 3
- Junaid Mansuri | robot-return-to-origin | Solution in Python 3 (~beats 99%) ( one line ) | junaidmansuri | 11 | 1,600 | robot return to origin | 657 | 0.753 | Easy | 10,943 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1127947/Simple-1-liner-in-Python-Faster-than-98 | class Solution:
def judgeCircle(self, m: str) -> bool:
return m.count("D") == m.count("U") and m.count("R") == m.count("L") | robot-return-to-origin | Simple 1 liner in Python; Faster than 98% | Annushams | 2 | 178 | robot return to origin | 657 | 0.753 | Easy | 10,944 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2171765/Simplest-Approach-oror-Move-Mapping | class Solution:
def judgeCircle(self, moves: str) -> bool:
moveMap = {
'R' : [0, 1],
'L' : [0, -1],
'U' : [1, 0],
'D' : [-1, 0]
}
startX = 0
startY = 0
for move in moves:
direction = moveMap[move]
startX += direction[0]
startY += direction[1]
if [startX, startY] == [0, 0]:
return True
else:
return False | robot-return-to-origin | Simplest Approach || Move Mapping | Vaibhav7860 | 1 | 44 | robot return to origin | 657 | 0.753 | Easy | 10,945 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2159294/Python3-is-the-solution-is-O(n)-runtime-and-O(1) | class Solution:
def judgeCircle(self, moves: str) -> bool:
x, y = 0, 0
for i in moves.lower():
if i == 'u':
y += 1
elif i == 'r':
x += 1
elif i == 'd':
y -= 1
elif i == 'l':
x -= 1
return x == 0 and y == 0 | robot-return-to-origin | Python3 is the solution is O(n) runtime and O(1) | arshergon | 1 | 81 | robot return to origin | 657 | 0.753 | Easy | 10,946 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1595918/Simple-approach-using-complex-numbers-(Python-3) | class Solution:
def judgeCircle(self, moves: str) -> bool:
direction = {
'U': 1j,
'D': -1j,
'L': -1,
'R': 1,
}
return sum(direction[m] for m in moves) == 0 | robot-return-to-origin | Simple approach using complex numbers (Python 3) | emwalker | 1 | 27 | robot return to origin | 657 | 0.753 | Easy | 10,947 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1534587/Python-83-Faster-Solution-with-if-elif-else | class Solution:
def judgeCircle(self, moves: str) -> bool:
X = Y = 0
for s in moves:
if s == "U":
X += 1
elif s == "D":
X -= 1
elif s == "R":
Y += 1
else:
Y -= 1
return X == False and Y == False | robot-return-to-origin | Python 83% Faster Solution with if, elif, else | aaffriya | 1 | 119 | robot return to origin | 657 | 0.753 | Easy | 10,948 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1332782/Easy-to-understand-with-explaination. | class Solution:
def judgeCircle(self, moves: str) -> bool:
x=y=0
for i in moves:
if i=="U":
y+=1
elif i=="D":
y-=1
elif i=="L":
x+=1
elif i=="R":
x-=1
if x==y==0:
return True
return False | robot-return-to-origin | Easy to understand with explaination. | souravsingpardeshi | 1 | 97 | robot return to origin | 657 | 0.753 | Easy | 10,949 |
https://leetcode.com/problems/robot-return-to-origin/discuss/527471/Python-one-liner-99.3-faster-100-mem | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count("L") == moves.count("R") and moves.count("U") == moves.count("D") | robot-return-to-origin | Python one liner 99.3 % faster, 100% mem | stefanbalas | 1 | 147 | robot return to origin | 657 | 0.753 | Easy | 10,950 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2803806/Simple-counting | class Solution:
def judgeCircle(self, moves: str) -> bool:
count = {'U': 0, 'L': 0}
for x in moves:
if x == 'U':
count['U'] += 1
elif x == 'D':
count['U'] -= 1
elif x == 'L':
count['L'] += 1
else:
count['L'] -= 1
return count['U'] == 0 and count['L'] == 0 | robot-return-to-origin | Simple counting | js44lee | 0 | 1 | robot return to origin | 657 | 0.753 | Easy | 10,951 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2797560/Simple-Python-Solution | class Solution:
def judgeCircle(self, moves: str) -> bool:
a=0
b=0
for move in moves:
if move=="U":
a+=1
elif move=="R":
b+=1
elif move=="L":
b-=1
elif move=="D":
a-=1
if a==0 and b==0:
return 1
else:
return 0 | robot-return-to-origin | Simple Python Solution | sbhupender68 | 0 | 1 | robot return to origin | 657 | 0.753 | Easy | 10,952 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2791812/Python-solution | class Solution:
def judgeCircle(self, moves: str) -> bool:
a = b = 0
for i in moves:
if i == 'U':
a += 1
elif i == "D":
a -= 1
elif i == "L":
b += 1
else:
b -= 1
return a == 0 and b == 0 | robot-return-to-origin | Python solution | shingnapure_shilpa17 | 0 | 2 | robot return to origin | 657 | 0.753 | Easy | 10,953 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2779086/Python-or-Simple | class Solution:
def judgeCircle(self, moves: str) -> bool:
x=Counter(moves)
return x["D"]==x["U"] and x["R"]==x["L"] | robot-return-to-origin | Python | Simple | Chetan_007 | 0 | 1 | robot return to origin | 657 | 0.753 | Easy | 10,954 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2773296/Python-One-Liner | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D') | robot-return-to-origin | Python One Liner | dnvavinash | 0 | 2 | robot return to origin | 657 | 0.753 | Easy | 10,955 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2752574/easy-to-understand! | class Solution:
def judgeCircle(self, moves: str) -> bool:
x = 0
y = 0
for move in moves:
if(move=='U'):
y+=1
elif(move=='R'):
x+=1
elif(move=='D'):
y-=1
elif(move=='L'):
x-=1
return x==0 and y==0 | robot-return-to-origin | easy to understand! | sanjeevpathak | 0 | 2 | robot return to origin | 657 | 0.753 | Easy | 10,956 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2694172/Easy-to-Understand | class Solution:
def judgeCircle(self, moves: str) -> bool:
counter_Y=0
counter_X=0
for i in moves:
if i=="U":
counter_Y+=1
if i=="D":
counter_Y-=1
if i=="R":
counter_X+=1
if i=="L":
counter_X-=1
if counter_Y==0 and counter_X==0:
return True
else:
return False | robot-return-to-origin | Easy to Understand | prashantdahiya711 | 0 | 6 | robot return to origin | 657 | 0.753 | Easy | 10,957 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2564980/Solution | class Solution:
def judgeCircle(self, moves: str) -> bool:
if ((moves.count("R") == moves.count("L")) and (moves.count("U") == moves.count("D"))):
return True
return False | robot-return-to-origin | Solution | fiqbal997 | 0 | 30 | robot return to origin | 657 | 0.753 | Easy | 10,958 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2483909/Clean-and-well-structured-Python3-implementation-(Top-99.9) | class Solution:
def judgeCircle(self, moves: str) -> bool:
x=Counter(moves)
flag=False
if(x['U']==x['D'] and x['L']==x['R']):
flag=True
return flag | robot-return-to-origin | βοΈ Clean and well structured Python3 implementation (Top 99.9%) | explusar | 0 | 6 | robot return to origin | 657 | 0.753 | Easy | 10,959 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2156475/Two-solutions-(1-not-optimal-but-cool-%3A) | class Solution:
def judgeCircle(self, moves: str) -> bool:
# use 4 variables to keep counts of moves
# if the robot returns to the origin, all moves must cancel out to their opposite
# so up must cancel down and right must cancel left (i.e. opposites must share the # same count)
# return the moves opposite to one another being equal
# Time: O(n^4) Space: O(1)
return moves.count("L") == moves.count("R") and moves.count("U") == moves.count("D") | robot-return-to-origin | Two solutions (1 not optimal but cool :) | andrewnerdimo | 0 | 18 | robot return to origin | 657 | 0.753 | Easy | 10,960 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2156475/Two-solutions-(1-not-optimal-but-cool-%3A) | class Solution:
def judgeCircle(self, moves: str) -> bool:
# iterative
# use x, y axis to keep track of position
# increment/decrement x for right/left respectively
# increment/decrement y for up/down respectively
# return x as 0 & y as 0 (at start)
# Time: O(N) Space: O(1)
x = y = 0
for move in moves:
if move == "U":
y += 1
if move == "D":
y -= 1
if move == "R":
x += 1
if move == "L":
x -= 1
return x == y == 0 | robot-return-to-origin | Two solutions (1 not optimal but cool :) | andrewnerdimo | 0 | 18 | robot return to origin | 657 | 0.753 | Easy | 10,961 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2060217/Python-simple-oneliner | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R') | robot-return-to-origin | Python simple oneliner | StikS32 | 0 | 25 | robot return to origin | 657 | 0.753 | Easy | 10,962 |
https://leetcode.com/problems/robot-return-to-origin/discuss/2025451/Python3-or-Easy-solution-or-Faster-than-96 | class Solution:
def judgeCircle(self, moves: str) -> bool:
if(moves.count("L")==moves.count("R") and moves.count("U")==moves.count("D")):
return True
else:
return False | robot-return-to-origin | Python3 | Easy solution | Faster than 96% | user9273M | 0 | 64 | robot return to origin | 657 | 0.753 | Easy | 10,963 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1940092/Python-Clean-and-Simple-%2B-One-Liner | class Solution:
def judgeCircle(self, moves):
x = y = 0
for move in moves:
match move:
case "U": y += 1
case "D": y -= 1
case "R": x += 1
case "L": x -= 1
return x == y == 0 | robot-return-to-origin | Python - Clean and Simple + One-Liner | domthedeveloper | 0 | 52 | robot return to origin | 657 | 0.753 | Easy | 10,964 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1940092/Python-Clean-and-Simple-%2B-One-Liner | class Solution:
def judgeCircle(self, moves):
c = Counter(moves)
return c["U"] == c["D"] and c["L"] == c["R"] | robot-return-to-origin | Python - Clean and Simple + One-Liner | domthedeveloper | 0 | 52 | robot return to origin | 657 | 0.753 | Easy | 10,965 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1940092/Python-Clean-and-Simple-%2B-One-Liner | class Solution:
def judgeCircle(self, moves):
return (lambda c : c["U"] == c["D"] and c["L"] == c["R"])(Counter(moves)) | robot-return-to-origin | Python - Clean and Simple + One-Liner | domthedeveloper | 0 | 52 | robot return to origin | 657 | 0.753 | Easy | 10,966 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1897099/Python-Solution-(one-line) | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('L')==moves.count('R') and moves.count('U')==moves.count('D') | robot-return-to-origin | Python Solution (one line) | dinesh1898 | 0 | 24 | robot return to origin | 657 | 0.753 | Easy | 10,967 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1764486/Python3-solution | class Solution:
def judgeCircle(self, moves: str) -> bool:
if list(moves).count("R") == list(moves).count("L") and list(moves).count("U") == list(moves).count("D"):
return True
else:
return False | robot-return-to-origin | Python3 solution | liontamerowa | 0 | 29 | robot return to origin | 657 | 0.753 | Easy | 10,968 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1684402/Python-string.count() | class Solution:
def judgeCircle(self, moves: str) -> bool:
"""
Don't simulate. Use string count method to check if
number-left==number-right
and
number-up==number-down
"""
return (moves.count('L')==moves.count('R') and moves.count('U')==moves.count('D')) | robot-return-to-origin | Python string.count() | odinsraven | 0 | 36 | robot return to origin | 657 | 0.753 | Easy | 10,969 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1307168/Python3-dollarolution | class Solution:
def judgeCircle(self, moves: str) -> bool:
d = {'U': 0, 'R': 0, 'L': 0, 'D': 0}
for i in moves:
d[i] += 1
return (d['U'] == d['D'] and d['R'] == d['L']) | robot-return-to-origin | Python3 $olution | AakRay | 0 | 57 | robot return to origin | 657 | 0.753 | Easy | 10,970 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1273993/Easy-Python-Solution(90.51) | class Solution:
def judgeCircle(self, moves: str) -> bool:
d=Counter(moves)
return d['U']==d['D'] and d['L']==d['R'] | robot-return-to-origin | Easy Python Solution(90.51%) | Sneh17029 | 0 | 111 | robot return to origin | 657 | 0.753 | Easy | 10,971 |
https://leetcode.com/problems/robot-return-to-origin/discuss/1107745/My-python-solution | class Solution:
def judgeCircle(self, moves: str) -> bool:
x,y=0,0
for i in range(len(moves)):
if (moves[i] == 'L'):
x += 1;
if (moves[i] == 'R'):
x -= 1;
if (moves[i] == 'U'):
y += 1;
if (moves[i] == 'D'):
y -= 1;
return x==0 and y==0 | robot-return-to-origin | My python solution | 190031299-Daiva | 0 | 39 | robot return to origin | 657 | 0.753 | Easy | 10,972 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1310805/Python-Solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# first binary search where the value 'x' should be in the sorted array
n = len(arr)
low, high = 0, n - 1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == x:
start, end = mid - 1, mid + 1
k -= 1
break
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
if low > high:
start = high
end = low
# after we found where 'x' should be in the sorted array we expand to the left and to the right to find the next values until k (using two pointers start, end)
while k > 0:
if start == -1:
end += 1
elif end == n:
start -= 1
else:
if abs(arr[start] - x) <= abs(arr[end] - x):
start -= 1
else:
end += 1
k -= 1
return arr[start + 1:end] | find-k-closest-elements | Python Solution | mariandanaila01 | 13 | 1,000 | find k closest elements | 658 | 0.468 | Medium | 10,973 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2638447/python3-O(n)-time-complexity-and-efficient-algorithm | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left=0
right=len(arr) - 1
while right-left+1 > k:
if abs(x-arr[left]) > abs(x-arr[right]):
left+=1
else:
right-=1
return arr[left:right+1]
# time and space complexity
# time: O(n)
# space: O(1) | find-k-closest-elements | python3 O(n) time complexity and efficient algorithm | benon | 10 | 277 | find k closest elements | 658 | 0.468 | Medium | 10,974 |
https://leetcode.com/problems/find-k-closest-elements/discuss/625408/Python%3A-Binary-Search-to-solve-this-problem | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left = 0
right = len(arr) - k
while left < right:
mid = (left + right) // 2
midValue = arr[mid]
if x - arr[mid+k] <= midValue - x:
right = mid
else:
left = mid + 1
return arr[left : left + k] | find-k-closest-elements | Python: Binary Search to solve this problem | 241321 | 7 | 935 | find k closest elements | 658 | 0.468 | Medium | 10,975 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2603299/python-or-binary-search-or-two-pointers-or-two-solutions-or-O(n) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# find the closest number
right = self.getClosetNumber(arr, x)
left = right - 1
# get the pointers array
for _ in range(k):
if self.getLeftCloserNumber(arr, left, right, x) == right:
right += 1
else:
left -= 1
left = 0 if right - k < 0 else right - k
print(left, right)
return arr[left:] if left == right else arr[left:right]
def getClosetNumber(self, nums, target):
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid
else:
right = mid
return self.getLeftCloserNumber(nums, left, right, target)
def getLeftCloserNumber(self, nums, left, right, target):
if left < 0:
return right
if right > len(nums) - 1:
return left
return left if abs(nums[left] - target) <= abs(nums[right] - target) else right | find-k-closest-elements | python | binary-search | two pointers | two solutions | O(n) | MichelleZou | 4 | 215 | find k closest elements | 658 | 0.468 | Medium | 10,976 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2603299/python-or-binary-search-or-two-pointers-or-two-solutions-or-O(n) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# use two mid pointes method
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) // 2
# mid + k must not out of range
if abs(arr[mid] - x) > abs(arr[mid + k] - x):
left = mid + 1
# if All duplicate and the first one is large than x
# arr[mid] < x need to filter out this kind of case: [1,1,2,2,2,2,2,2,2,2] 3 1
elif arr[mid] == arr[mid + k] and arr[mid] < x:
left = mid + 1
else:
right = mid
return arr[left: left + k] | find-k-closest-elements | python | binary-search | two pointers | two solutions | O(n) | MichelleZou | 4 | 215 | find k closest elements | 658 | 0.468 | Medium | 10,977 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636932/Python-solution-using-lambda-function | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
arr.sort(key = lambda i:abs(i-x))
return sorted(arr[:k]) | find-k-closest-elements | Python solution using lambda function | Sahil1729 | 3 | 26 | find k closest elements | 658 | 0.468 | Medium | 10,978 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1310726/Easy-and-simple-solution-using-Binary-search-in-python | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left ,right= 0, len(arr) - k
while left < right:
mid = (left + right) // 2
if x - arr[mid] > arr[mid + k] - x: # to check that the element at arr[mid] is closer to x than arr[mid + k] or not
left = mid + 1
else:
right = mid
return arr[left:left + k] | find-k-closest-elements | Easy and simple solution using Binary search in python | maitysourab | 3 | 161 | find k closest elements | 658 | 0.468 | Medium | 10,979 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636689/SIMPLE-PYTHON3-SOLUTION-using-binary-search | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# first binary search where the value 'x' should be in the sorted array
n = len(arr)
low, high = 0, n - 1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == x:
start, end = mid - 1, mid + 1
k -= 1
break
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
if low > high:
start = high
end = low
# after we found where 'x' should be in the sorted array we expand to the left and to the right to find the next values until k (using two pointers start, end)
while k > 0:
if start == -1:
end += 1
elif end == n:
start -= 1
else:
if abs(arr[start] - x) <= abs(arr[end] - x):
start -= 1
else:
end += 1
k -= 1
return arr[start + 1:end] | find-k-closest-elements | β
β SIMPLE PYTHON3 SOLUTION β
β using binary search | rajukommula | 2 | 86 | find k closest elements | 658 | 0.468 | Medium | 10,980 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1057212/PythonPython3-Find-K-Closest-Elements-or-One-Liner | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(arr, key=lambda p: abs(p-x))[:k]) | find-k-closest-elements | [Python/Python3] Find K Closest Elements | One-Liner | newborncoder | 2 | 240 | find k closest elements | 658 | 0.468 | Medium | 10,981 |
https://leetcode.com/problems/find-k-closest-elements/discuss/368156/Solution-in-Python-3-(-one-line-) | class Solution:
def findClosestElements(self, N: List[int], k: int, x: int) -> List[int]:
A = sorted(N, key = lambda n: abs(x-n))
B = A[0:k]
C = sorted(B)
return C | find-k-closest-elements | Solution in Python 3 ( one line ) | junaidmansuri | 2 | 616 | find k closest elements | 658 | 0.468 | Medium | 10,982 |
https://leetcode.com/problems/find-k-closest-elements/discuss/368156/Solution-in-Python-3-(-one-line-) | class Solution:
def findClosestElements(self, N: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(N, key = lambda n: abs(x-n))[:k])
- Junaid Mansuri
(LeetCode ID)@hotmail.com | find-k-closest-elements | Solution in Python 3 ( one line ) | junaidmansuri | 2 | 616 | find k closest elements | 658 | 0.468 | Medium | 10,983 |
https://leetcode.com/problems/find-k-closest-elements/discuss/235075/python3-3-line-solution-using-sorted() | class Solution:
def findClosestElements(self, arr, k, x):
if x >= arr[-1]: return arr[-k:]
if x <= arr[0]: return arr[:k]
return sorted(sorted(arr, key=lambda element: abs(element-x))[0:k]) | find-k-closest-elements | python3 3 line solution using `sorted()` | ocawa | 2 | 154 | find k closest elements | 658 | 0.468 | Medium | 10,984 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2640236/Python-one-line-solution-or-heapq.nsmallest | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(heapq.nsmallest(k, arr, key=lambda i: abs(i-x+.1))) | find-k-closest-elements | Python one line solution | heapq.nsmallest | AgentIvan | 1 | 10 | find k closest elements | 658 | 0.468 | Medium | 10,985 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2638381/python3-solution-using-heap-(Priority-queue)-or-O(n-%2B-klogk)-time | class Solution:
# O(n + klogk) time,
# O(n) space,
# Approach: heap, sorting
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
ans = []
n = len(arr)
min_heap = []
for i in range(n):
heapq.heappush(min_heap, (abs(arr[i]-x), arr[i]))
while k > 0:
ans.append(heapq.heappop(min_heap)[1])
k -=1
ans.sort()
return ans | find-k-closest-elements | python3 solution using heap (Priority queue) | O(n + klogk) time | destifo | 1 | 30 | find k closest elements | 658 | 0.468 | Medium | 10,986 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2638339/Two-pointers-binary-search-python3-solution-or-O(logn-%2B-k)-time | class Solution:
# O(logn + k) time,
# O(k) space,
# Approach: Binary search, two pointers, queue
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
ans = deque()
def binarySearch(num: int, arr: List[int]) -> int:
lo, hi = 0, len(arr)-1
while lo <= hi:
mid = (hi+lo)//2
curr_num = arr[mid]
if curr_num == num:
return mid
elif curr_num > num:
hi = mid-1
else:
lo = mid+1
return lo
x_index = binarySearch(x, arr)
l, r = x_index-1, x_index
n = len(arr)
while l >= 0 or r < n:
if len(ans) == k:
break
left_estimate = float('inf')
if l >= 0:
left_estimate = abs(arr[l]-x)
right_estimate = float('inf')
if r < n:
right_estimate = abs(arr[r]-x)
if left_estimate > right_estimate:
ans.append(arr[r])
r +=1
else:
ans.appendleft(arr[l])
l -=1
return ans | find-k-closest-elements | Two pointers binary search python3 solution | O(logn + k) time | destifo | 1 | 24 | find k closest elements | 658 | 0.468 | Medium | 10,987 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2637601/GolangPython-O(log(N)%2Bk)-time-or-O(K)-space | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left = 0
middle = 0
right = len(arr)-1
while left < right:
middle = (left+right)//2
if arr[middle] == x:
break
elif arr[middle] < x:
if middle == len(arr)-1:
break
if arr[middle+1] > x:
if compare(arr[middle+1],arr[middle],x):
middle+=1
break
left = middle+1
elif arr[middle] > x:
if middle == 0:
break
if arr[middle-1] < x:
if compare(arr[middle-1],arr[middle],x):
middle-=1
break
right = middle-1
left_bound = middle
right_bound = middle
l = middle-1
r = middle+1
while right_bound - left_bound + 1 < k:
l_item = arr[l] if l >= 0 else float("inf")
r_item = arr[r] if r < len(arr) else float("inf")
if compare(l_item,r_item,x):
left_bound-=1
l-=1
else:
right_bound+=1
r+=1
return arr[left_bound:right_bound+1]
def compare(a,b,x):
return abs(a - x) < abs(b - x) or abs(a - x) == abs(b - x) and (a < b) | find-k-closest-elements | Golang/Python O(log(N)+k) time | O(K) space | vtalantsev | 1 | 35 | find k closest elements | 658 | 0.468 | Medium | 10,988 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2637092/Python-Solution-or-Heap-or-Priority-Queue | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
heap=[]
n=len(arr)
for i in range(n):
heapq.heappush(heap, [abs(arr[i]-x), arr[i]])
ans=[]
while k>0:
ans.append(heapq.heappop(heap)[1])
k-=1
ans.sort()
return ans | find-k-closest-elements | Python Solution | Heap | Priority Queue | Siddharth_singh | 1 | 45 | find k closest elements | 658 | 0.468 | Medium | 10,989 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636632/python3-or-very-easy-or-explained-or-5-lines-of-code | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
lst=[] # list initialize
for e in arr: lst.append((abs(e - x), e)) # getting distance with element
lst.sort() # sort list to get dist in increasing order
res = [e[1] for e in lst[:k]] # get first k closest element
return sorted(res) # return first k closest in increasing order | find-k-closest-elements | python3 | very easy | explained | 5 lines of code | H-R-S | 1 | 12 | find k closest elements | 658 | 0.468 | Medium | 10,990 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1762257/simple-python-window | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
lo = 0
hi = len(arr)-k
while lo < hi:
mid = (lo+hi)//2
if x - arr[mid]> arr[mid+k] -x:
lo = mid+1
else:
hi = mid
return arr[lo:lo+k] | find-k-closest-elements | simple python window | gasohel336 | 1 | 115 | find k closest elements | 658 | 0.468 | Medium | 10,991 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1518175/Python3-solutions-with-comments | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
count = 0
res = []
d = {}
if k == len(arr): # lucky case when we return all elements because we have k greater than length of arr
return arr
for i in range(len(arr)): # making a dictionary with all indexes and their distance
if i not in d:
d[i] = abs(arr[i] - x)
d = dict(sorted(d.items(), key=lambda item: item[1])) # sort dictionary in ascending order
for i, element in enumerate(d):
res.append(arr[element])
count += 1
if count == k: break
return sorted(res) # we sort here because we can have abs(arr[i]-x) == abs(arr[j]-x) and we need min(arr[i], arr[j]) | find-k-closest-elements | Python3 solutions with comments | FlorinnC1 | 1 | 182 | find k closest elements | 658 | 0.468 | Medium | 10,992 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1518175/Python3-solutions-with-comments | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
if len(arr) <= k: return arr # basic case
count = 0
res = []
if x <= arr[0]: # the values is smaller than the first edge so we return all element from 0 -> k
for i in range(len(arr)):
res.append(arr[i])
count += 1
if count == k:
return res
elif x >= arr[-1]: # the values is bigger than the last edge so we return all element from last index -> last index - k
for i in range(len(arr)-1,-1,-1):
res.insert(0, arr[i])
count += 1
if count == k:
return res
else: # two pointers approach
smallest_distance = math.inf
for i in range(len(arr)):
if smallest_distance > abs(arr[i]-x):
smallest_distance = abs(arr[i]-x)
smallest_index = i
i = smallest_index
j = smallest_index + 1
while count != k:
while i >= 0 and abs(arr[i]-x) <= abs(arr[j]-x) and count != k:
res.insert(0, arr[i])
i -= 1
count += 1
if i < 0 and count != k: # we've reached the first edge(arr[0] inserted ) so we look at the right side
while j < len(arr) and count != k:
res.append(arr[j])
j += 1
count += 1
while j < len(arr) and abs(arr[i]-x) > abs(arr[j]-x) and count != k:
res.append(arr[j])
j += 1
count += 1
if j > len(arr)-1 and count != k: # we've reached the last edge(arr[-1] inserted ) so we look at left side
while i >= 0 and count != k:
res.insert(0, arr[i])
i -= 1
count += 1
return res | find-k-closest-elements | Python3 solutions with comments | FlorinnC1 | 1 | 182 | find k closest elements | 658 | 0.468 | Medium | 10,993 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1075576/Python-easy-understanding-version-and-improved-version | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Binary Search
# Set right to (len(arr) - k) so that (middle + k) will always valid since middle will not equal to right and (right + k - 1) is always valid
left, right = 0, len(arr) - k
while left < right:
# left ... middle ... middle + k ... high
middle = (left + right) // 2
# left_bound lies on the left side of MIDDLE
if x <= arr[middle]:
right = middle
# left_bound lies on the right side of MIDDLE
elif x >= arr[middle + k]:
left = middle + 1
# left_bound lies between MIDDLE and MIDDLE + k
else:
# Distence from middle and middle + k
middist = abs(arr[middle] - x)
kdist = abs(arr[middle + k] - x)
if middist <= kdist:
right = middle
else:
left = middle + 1
return arr[right : right + k] | find-k-closest-elements | Python easy understanding version and improved version | liangcode | 1 | 218 | find k closest elements | 658 | 0.468 | Medium | 10,994 |
https://leetcode.com/problems/find-k-closest-elements/discuss/1075576/Python-easy-understanding-version-and-improved-version | class Solution:
def findClosestElements(self, arr, k, x):
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) // 2
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left:left + k] | find-k-closest-elements | Python easy understanding version and improved version | liangcode | 1 | 218 | find k closest elements | 658 | 0.468 | Medium | 10,995 |
https://leetcode.com/problems/find-k-closest-elements/discuss/895034/Python3-binary-search-O(K-%2B-logN) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(arr, key=lambda n: (abs(x-n), n))[:k]) | find-k-closest-elements | [Python3] binary search O(K + logN) | ye15 | 1 | 115 | find k closest elements | 658 | 0.468 | Medium | 10,996 |
https://leetcode.com/problems/find-k-closest-elements/discuss/895034/Python3-binary-search-O(K-%2B-logN) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
hi = bisect_left(arr, x)
lo = hi - 1
ans = deque()
for _ in range(k):
if len(arr) <= hi or 0 <= lo and x - arr[lo] <= arr[hi] - x:
ans.appendleft(arr[lo])
lo -= 1
else:
ans.append(arr[hi])
hi += 1
return ans | find-k-closest-elements | [Python3] binary search O(K + logN) | ye15 | 1 | 115 | find k closest elements | 658 | 0.468 | Medium | 10,997 |
https://leetcode.com/problems/find-k-closest-elements/discuss/895034/Python3-binary-search-O(K-%2B-logN) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
lo, hi = 0, len(arr)-k
while lo < hi:
mid = lo + hi >> 1
if x - arr[mid] > arr[mid+k] - x: lo = mid + 1
else: hi = mid
return arr[lo:lo+k] | find-k-closest-elements | [Python3] binary search O(K + logN) | ye15 | 1 | 115 | find k closest elements | 658 | 0.468 | Medium | 10,998 |
https://leetcode.com/problems/find-k-closest-elements/discuss/718685/Python3-two-solutions-Find-K-Closest-Elements | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
class Wrapper:
def __getitem__(self, i):
return arr[i] - x + arr[i+k] - x
r = bisect.bisect_left(Wrapper(), 0, 0, len(arr) - k)
return arr[r:r+k] | find-k-closest-elements | Python3 two solutions - Find K Closest Elements | r0bertz | 1 | 453 | find k closest elements | 658 | 0.468 | Medium | 10,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.