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 ... | 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.r... | 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:
s... | 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)
Inor... | 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:
... | 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(... | 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... | 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:
... | 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.va... | 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.findTar... | 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)
... | 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]... | 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,l... | 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... | 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
... | 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)
... | 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 ... | 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, ... | 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
... | 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)
#... | 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.constructMaximumB... | 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)
ret... | 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:... | 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])
... | 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), ar... | 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.... | 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.constr... | 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()
... | 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) == ... | 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
... | 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(pre... | 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.rig... | 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[ind... | 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.constructMaximumBinaryTre... | 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: ... | 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
... | 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.... | 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 I... | 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_hei... | 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 vi... | 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]
... | 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 -= ... | 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
... | 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:
retur... | 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:
... | 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... | 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 ... | 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'):
... | 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":
... | 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)
... | 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)
# Tim... | 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'... | 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:
... | 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... | 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:
... | 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, ... | 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] - ... | 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]... | 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:
... | 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... | 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
... | 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:
... | 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
... | 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... | 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[... | 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)): # mak... | 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... | 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
whil... | 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 ... | 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])
... | 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.