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/insert-into-a-binary-search-tree/discuss/1293854/Python-Recursive-Solution-or8-Lines-Code-or-Runtime-greater83.00-Memorygreater-94 | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if root == None:
return TreeNode(val)
else:
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
if root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root | insert-into-a-binary-search-tree | Python Recursive Solution |8 Lines Code | Runtime >83.00%, Memory> 94% | poojakhatri888 | 1 | 119 | insert into a binary search tree | 701 | 0.746 | Medium | 11,600 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1073632/Elegant-Python-Recursion-faster-than-98.46 | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
elif root.val < val:
root.right = self.insertIntoBST(root.right, val)
else:
root.left = self.insertIntoBST(root.left, val)
return root | insert-into-a-binary-search-tree | Elegant Python Recursion, faster than 98.46% | 111989 | 1 | 83 | insert into a binary search tree | 701 | 0.746 | Medium | 11,601 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/881921/Two-Python-Solutions-Explained-(video-%2B-code) | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
elif val > root.val:
#right
root.right = self.insertIntoBST(root.right, val)
else:
#left
root.left = self.insertIntoBST(root.left, val)
return root | insert-into-a-binary-search-tree | Two Python Solutions Explained (video + code) | spec_he123 | 1 | 204 | insert into a binary search tree | 701 | 0.746 | Medium | 11,602 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/881921/Two-Python-Solutions-Explained-(video-%2B-code) | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
s = []
def inorder(root):
if root:
inorder(root.left)
s.append(root.val)
inorder(root.right)
inorder(root)
s.append(val)
s.sort()
def listtoBST(l):
if not l:
return None
mid = len(l) // 2
root = TreeNode(l[mid])
root.left = listtoBST(l[:mid])
root.right = listtoBST(l[mid + 1 :])
return root
return listtoBST(s) | insert-into-a-binary-search-tree | Two Python Solutions Explained (video + code) | spec_he123 | 1 | 204 | insert into a binary search tree | 701 | 0.746 | Medium | 11,603 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/298288/Python-faster-than-96-100-ms | class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if root==None:
return TreeNode(val)
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root | insert-into-a-binary-search-tree | Python - faster than 96%, 100 ms | il_buono | 1 | 367 | insert into a binary search tree | 701 | 0.746 | Medium | 11,604 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2837014/Python-or-insertIntoBST-or-Easy-solution-with-explanation-or-O(Log(N)) | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
temp = root
node = TreeNode(val)
while(temp):
if temp.val > val:
if temp.left:
temp = temp.left
else:
temp.left = node
break
else:
if temp.right:
temp = temp.right
else:
temp.right = node
break
if root:
return root
else:
return node | insert-into-a-binary-search-tree | Python | insertIntoBST | Easy solution with explanation | O(Log(N)) | utkarshjain | 0 | 1 | insert into a binary search tree | 701 | 0.746 | Medium | 11,605 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2794710/easy-python-solution | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root == None:
return TreeNode(val)
if val < root.val: root.left = self.insertIntoBST(root.left,val)
else: root.right = self.insertIntoBST(root.right,val)
return root | insert-into-a-binary-search-tree | easy python solution | betaal | 0 | 2 | insert into a binary search tree | 701 | 0.746 | Medium | 11,606 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2596260/Python3-or-Intuitive-DFS-or-Neat | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
def rec(n = root, l = -inf, h = inf):
if val < n.val:
if not n.left:
n.left = TreeNode(val)
return root
return rec(n.left, l, n.val)
if not n.right:
n.right = TreeNode(val)
return root
return rec(n.right, n.val, h)
return rec() | insert-into-a-binary-search-tree | Python3 | Intuitive DFS | Neat | aashi111989 | 0 | 24 | insert into a binary search tree | 701 | 0.746 | Medium | 11,607 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2587786/Python-Easy-To-Understand-or-Beginner-Friendly | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
'''
1. if root is empty or null we will create a new node
2. if the value is less than the root value then we will insert it into the left part of the tree
3. if the value is greater than the root value then we will insert the node in the right part of the tree.
'''
if not root: #1
return TreeNode(val)
if val > root.val: #2
root.right = self.insertIntoBST(root.right,val)
elif val < root.val: #3
root.left = self.insertIntoBST(root.left,val)
return root | insert-into-a-binary-search-tree | Python Easy To Understand | Beginner Friendly | Ron99 | 0 | 32 | insert into a binary search tree | 701 | 0.746 | Medium | 11,608 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2397149/Python-Iterative-Solution-oror-Documented | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# if tree is empty, return the root with given value
if not root: return TreeNode(val)
# take copy of root, so that we can retain the root
curNode = root
# traverse until we found the position of the given value to insert
while curNode:
if val < curNode.val:
if curNode.left:
curNode = curNode.left
else:
curNode.left = TreeNode(val) # add the new value at left of curNode
break
else:
if curNode.right:
curNode = curNode.right
else:
curNode.right = TreeNode(val) # add the new value at right of curNode
break
return root # return root | insert-into-a-binary-search-tree | [Python] Iterative Solution || Documented | Buntynara | 0 | 15 | insert into a binary search tree | 701 | 0.746 | Medium | 11,609 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/2033107/Python-Simple-readable-easy-to-understand-recursive-solution-(140-ms) | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val, None, None)
self.traverse(root, None, val)
return root
def traverse(self, root: Optional[TreeNode], prev: Optional[TreeNode], val:int):
if root:
prev = root
if root.val > val:
self.traverse(root.left, prev, val)
else:
self.traverse(root.right, prev, val)
elif prev.val > val:
prev.left = TreeNode(val, None, None)
else:
prev.right = TreeNode(val, None, None) | insert-into-a-binary-search-tree | [Python] Simple, readable, easy to understand, recursive solution (140 ms) | FedMartinez | 0 | 43 | insert into a binary search tree | 701 | 0.746 | Medium | 11,610 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1853126/python-3-oror-simple-iterative-solution | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root is None:
return TreeNode(val)
cur = root
while True:
if val < cur.val:
if cur.left is None:
cur.left = TreeNode(val)
break
cur = cur.left
else:
if cur.right is None:
cur.right = TreeNode(val)
break
cur = cur.right
return root | insert-into-a-binary-search-tree | python 3 || simple iterative solution | dereky4 | 0 | 31 | insert into a binary search tree | 701 | 0.746 | Medium | 11,611 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1782542/Clean-Python3-solution | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
if val<root.val:
root.left=self.insertIntoBST(root.left,val)
if val>root.val:
root.right=self.insertIntoBST(root.right,val)
return root | insert-into-a-binary-search-tree | Clean Python3 solution | Karna61814 | 0 | 21 | insert into a binary search tree | 701 | 0.746 | Medium | 11,612 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1760181/Python-Code-or-Linear-O(N)-or-99-Faster | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
cur, next = None, root
while next:
cur = next
next = next.left if val < next.val else next.right
if val < cur.val:
cur.left = TreeNode(val)
else:
cur.right = TreeNode(val)
return root | insert-into-a-binary-search-tree | Python Code | Linear O(N) | 99% Faster | rackle28 | 0 | 20 | insert into a binary search tree | 701 | 0.746 | Medium | 11,613 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1684569/Python3-Iterative-Solution | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
node = root
prev = None
while node:
prev = node
if node.val > val:
node = node.left
else:
node = node.right
if prev.val > val:
prev.left = TreeNode(val)
else:
prev.right = TreeNode(val)
return root | insert-into-a-binary-search-tree | Python3 Iterative Solution | atiq1589 | 0 | 11 | insert into a binary search tree | 701 | 0.746 | Medium | 11,614 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1684280/Python-Simple-Python-Solution-Using-Recursion-and-Iterative-Approach | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
value = val
if root == None:
return TreeNode(value)
node = root
pre=0
while node != None:
if value < node.val:
pre=node
node = node.left
elif value > node.val:
pre=node
node = node.right
if value < pre.val:
pre.left = TreeNode(value)
elif value > pre.val:
pre.right = TreeNode(value)
return root | insert-into-a-binary-search-tree | [ Python ] ββ Simple Python Solution Using Recursion and Iterative Approach π₯β | ASHOK_KUMAR_MEGHVANSHI | 0 | 32 | insert into a binary search tree | 701 | 0.746 | Medium | 11,615 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1684280/Python-Simple-Python-Solution-Using-Recursion-and-Iterative-Approach | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root == None:
return TreeNode(val)
def CreateTree(node,value):
if node == None:
return TreeNode(value)
elif value<node.val:
node.left = CreateTree(node.left,value)
elif value>node.val:
node.right = CreateTree(node.right,value)
return node
CreateTree(root,val)
return root | insert-into-a-binary-search-tree | [ Python ] ββ Simple Python Solution Using Recursion and Iterative Approach π₯β | ASHOK_KUMAR_MEGHVANSHI | 0 | 32 | insert into a binary search tree | 701 | 0.746 | Medium | 11,616 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1684169/Python-3-EASY-Intuitive-Solution | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
node = TreeNode(val=val)
if not root:
return node
temp = root
prev = None
while temp:
prev = temp
if val > temp.val:
temp = temp.right
else:
temp = temp.left
if val > prev.val:
prev.right = node
else:
prev.left = node
return root | insert-into-a-binary-search-tree | β
[Python 3] EASY Intuitive Solution | JawadNoor | 0 | 11 | insert into a binary search tree | 701 | 0.746 | Medium | 11,617 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1672377/Python-andand-Kotlin-solutions | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
root = TreeNode(val)
return root
def insert_node(root, new_node):
if root.val > new_node:
if root.left:
insert_node(root.left, new_node)
else:
root.left = TreeNode(new_node)
elif root.val < new_node:
if root.right:
insert_node(root.right, new_node)
else:
root.right = TreeNode(new_node)
insert_node(root, val)
return root | insert-into-a-binary-search-tree | Python && Kotlin solutions | SleeplessChallenger | 0 | 49 | insert into a binary search tree | 701 | 0.746 | Medium | 11,618 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1146003/Python-Faster-Than-99.77 | class Solution:
# Traverses the binary tree to find a valid location to insert.
def traverse(self, cur:TreeNode, val: int):
if cur.left is not None and cur.val > val:
print(f'At {cur.val} we go left to {cur.left.val}')
return self.traverse(cur.left, val)
elif cur.right is not None and cur.val < val:
print(f'At {cur.val} we go right to {cur.right.val}')
return self.traverse(cur.right, val)
else:
print(f'At {cur.val} is a child. Can go no further')
return cur
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
leaf = self.traverse(root, val)
if leaf.val > val:
leaf.left = TreeNode(val)
elif leaf.val < val:
leaf.right = TreeNode(val)
return root | insert-into-a-binary-search-tree | Python Faster Than 99.77% | APet99 | 0 | 67 | insert into a binary search tree | 701 | 0.746 | Medium | 11,619 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1106619/Python3-Recursive-Easy | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
n = TreeNode(val)
return n
node = root
def helper(root,val):
# Left subtree
if root.val > val:
if root.left:
helper(root.left,val)
else:
root.left = TreeNode(val)
return
# Right subtree
if root.val < val:
if root.right:
helper(root.right,val)
else:
root.right = TreeNode(val)
return
helper(root,val)
return node | insert-into-a-binary-search-tree | Python3, Recursive, Easy | poorvakulz72 | 0 | 46 | insert into a binary search tree | 701 | 0.746 | Medium | 11,620 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1021569/Python3-simple-solution | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
def insert(x,val):
if x.val > val:
if x.left:
insert(x.left,val)
else:
x.left = TreeNode(val)
else:
if x.right:
insert(x.right,val)
else:
x.right = TreeNode(val)
if root != None:
insert(root,val)
else:
root = TreeNode(val)
return root | insert-into-a-binary-search-tree | Python3 simple solution | EklavyaJoshi | 0 | 53 | insert into a binary search tree | 701 | 0.746 | Medium | 11,621 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/960783/Iterative-Python-Solution | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
curr = root
prev = None
if root is None:
return TreeNode(val)
while root != None:
if root.val == val:
return curr
elif val < root.val:
prev = root
root = root.left
elif val > root.val:
prev = root
root = root.right
if root is None:
if val < prev.val:
prev.left = TreeNode(val)
root = prev
if val > prev.val:
prev.right = TreeNode(val)
root = prev
return curr | insert-into-a-binary-search-tree | Iterative Python Solution | tgoel219 | 0 | 107 | insert into a binary search tree | 701 | 0.746 | Medium | 11,622 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/883040/Python-Iterative-Solution | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
new_node = TreeNode(val)
if not root:
return new_node
node = root
while node:
if new_node.val < node.val:
if node.left:
node = node.left
else:
node.left = new_node
break
else:
if node.right:
node = node.right
else:
node.right = new_node
break
return root | insert-into-a-binary-search-tree | Python Iterative Solution | ehdwn1212 | 0 | 26 | insert into a binary search tree | 701 | 0.746 | Medium | 11,623 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/882368/Python-3-Faster-than-99.88-iterative-solution-and-short-recursive-solution | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
newNode = TreeNode(val)
if not root: return newNode
node = root
while(node):
if val < node.val:
if node.left:
node = node.left
else:
node.left = newNode
node = None
elif val > node.val:
if node.right:
node = node.right
else:
node.right = newNode
node = None
return root | insert-into-a-binary-search-tree | [Python 3] Faster than 99.88% iterative solution and short recursive solution | abstractart | 0 | 47 | insert into a binary search tree | 701 | 0.746 | Medium | 11,624 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/882368/Python-3-Faster-than-99.88-iterative-solution-and-short-recursive-solution | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root: return TreeNode(val)
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
elif val > root.val:
root.right = self.insertIntoBST(root.right, val)
return root | insert-into-a-binary-search-tree | [Python 3] Faster than 99.88% iterative solution and short recursive solution | abstractart | 0 | 47 | insert into a binary search tree | 701 | 0.746 | Medium | 11,625 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/715405/Python-Log(n)-Easy-to-Understand | class Solution:
# Time: O(log(n))
# Space: O(H)
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
elif val < root.val:
root.left = self.insertIntoBST(root.left, val)
return root | insert-into-a-binary-search-tree | Python Log(n) Easy to Understand | whissely | 0 | 97 | insert into a binary search tree | 701 | 0.746 | Medium | 11,626 |
https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/566722/python3 | class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
s = 'right' if val > root.val else 'left'
if getattr(root, s) is None:
setattr(root, s, TreeNode(val))
else:
self.insertIntoBST(getattr(root, s), val)
return root | insert-into-a-binary-search-tree | python3 | VicV13 | 0 | 58 | insert into a binary search tree | 701 | 0.746 | Medium | 11,627 |
https://leetcode.com/problems/binary-search/discuss/2700642/Python-Classic-Binary-Search-Problem-or-99-Faster-or-Fastest-Solution | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
right = mid-1
else:
left = mid+1
return -1 | binary-search | βοΈ Python Classic Binary Search Problem | 99% Faster | Fastest Solution | pniraj657 | 47 | 6,000 | binary search | 704 | 0.551 | Easy | 11,628 |
https://leetcode.com/problems/binary-search/discuss/1743624/Python-Simple-Python-Solution-Using-Binary-Search-With-Two-Approach | class Solution:
def search(self, nums: List[int], target: int) -> int:
low=0
high=len(nums)-1
while low <=high:
mid= (low+high)//2
if nums[mid]==target:
return mid
elif nums[mid]<target:
low=mid+1
elif nums[mid]>target:
high=mid-1
return -1 | binary-search | [ Python ] β
β
Simple Python Solution Using Binary Search With Two Approach π₯π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 12 | 1,200 | binary search | 704 | 0.551 | Easy | 11,629 |
https://leetcode.com/problems/binary-search/discuss/1743624/Python-Simple-Python-Solution-Using-Binary-Search-With-Two-Approach | class Solution:
def search(self, nums: List[int], target: int) -> int:
def BinarySearch(array, start, end, target):
if start <= end:
mid = (start + end)//2
if array[mid] == target:
return mid
elif array[mid] < target:
start = mid + 1
if array[mid] > target:
end = mid - 1
return BinarySearch(nums, start, end, target)
return -1
start = 0
end = len(nums)-1
result = BinarySearch(nums, start, end, target)
return result | binary-search | [ Python ] β
β
Simple Python Solution Using Binary Search With Two Approach π₯π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 12 | 1,200 | binary search | 704 | 0.551 | Easy | 11,630 |
https://leetcode.com/problems/binary-search/discuss/1479404/Clear-Binary-Search-Algorithm-with-one-post-oror-Thought-Process-explained | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left)//2
#Case 1
if nums[mid] == target:
return mid
#Case 2
if nums[mid] < target:
left = mid + 1
#Case 3
if nums[mid] > target:
right = mid - 1
#if the element is not present in the array
#the condition inside the while loop will fail and we will return -1
return -1 | binary-search | Clear Binary Search Algorithm with one post || Thought Process explained | aarushsharmaa | 10 | 1,100 | binary search | 704 | 0.551 | Easy | 11,631 |
https://leetcode.com/problems/binary-search/discuss/2592091/SIMPLE-PYTHON3-SOLUTION-O(logN) | class Solution:
def search(self, nums: List[int], target: int) -> int:
hi = len(nums)-1
lo = 0
while lo<=hi:
mid = (lo+hi)//2
if nums[mid]==target: return mid
if target>nums[mid]: lo = mid+1
else: hi = mid-1
return -1 | binary-search | β
β SIMPLE PYTHON3 SOLUTION β
βO(logN) | rajukommula | 6 | 1,100 | binary search | 704 | 0.551 | Easy | 11,632 |
https://leetcode.com/problems/binary-search/discuss/1883755/Python3-LOOOL-TOO-EZ-(D)-Explained | class Solution:
def search(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mi = (lo + hi) // 2
if nums[mi] == target:
return mi
if nums[mi] < target:
lo = mi + 1
else:
hi = mi - 1
return -1 | binary-search | βοΈ [Python3] LOOOL TOO EZ (Β΄Π`), Explained | artod | 6 | 288 | binary search | 704 | 0.551 | Easy | 11,633 |
https://leetcode.com/problems/binary-search/discuss/2802495/Python-simple-solution-to-Find-the-target-element-in-o(log-n)-using-Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums)-1
while l<=r:
mid = (l + r) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
l = mid + 1
else:
r = mid -1
return -1 | binary-search | π Python simple solution to Find the target element in o(log n) using Binary Search | Pragadeeshwaran_Pasupathi | 5 | 504 | binary search | 704 | 0.551 | Easy | 11,634 |
https://leetcode.com/problems/binary-search/discuss/1141678/Python3-simple-solution-beats-90-users | class Solution:
def search(self, nums: List[int], target: int) -> int:
def binSearch(low,high,nums):
if low <= high:
mid = (low+high)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
return binSearch(mid+1,high,nums)
else:
return binSearch(low,mid-1,nums)
else:
return -1
return binSearch(0,len(nums)-1,nums) | binary-search | Python3 simple solution beats 90% users | EklavyaJoshi | 5 | 308 | binary search | 704 | 0.551 | Easy | 11,635 |
https://leetcode.com/problems/binary-search/discuss/1539436/Python-98%2B%2B-Faster-O(logN)-Solution | class Solution:
def search(self, nums: List[int], key: int) -> int:
i, j = 0, len(nums)-1
while i <= j:
m = (i + j) // 2
mid = nums[m]
if mid > key : j = m - 1
elif mid < key : i = m + 1
else : return m
else:
return -1 | binary-search | Python 98%++ Faster O(logN) Solution | aaffriya | 4 | 910 | binary search | 704 | 0.551 | Easy | 11,636 |
https://leetcode.com/problems/binary-search/discuss/1495627/Faster-than-100-Binary-Search. | class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) // 2
if nums[mid] < target:
start = mid + 1
elif nums[mid] > target:
end = mid - 1
else:
return mid
return -1 | binary-search | Faster than 100%, Binary Search. | AmrinderKaur1 | 4 | 770 | binary search | 704 | 0.551 | Easy | 11,637 |
https://leetcode.com/problems/binary-search/discuss/1280562/Easy-Python-Solution(99.23) | class Solution:
def search(self, nums: List[int], target: int) -> int:
l=0
r=len(nums)
while(l<r):
m=l+(r-l)//2
# print(m)
if(nums[m]==target):
return m
elif(nums[m]<target):
l=m+1
else:
r=m
return -1 | binary-search | Easy Python Solution(99.23%) | Sneh17029 | 4 | 1,800 | binary search | 704 | 0.551 | Easy | 11,638 |
https://leetcode.com/problems/binary-search/discuss/381138/Two-Solutions-in-Python-3 | class Solution:
def search(self, n: List[int], t: int) -> int:
i, j = 0, len(n)-1
while j - i > 1:
m = (i+j)//2
if t <= n[m]: j = m
else: i = m
return i if n[i] == t else j if n[j] == t else -1 | binary-search | Two Solutions in Python 3 | junaidmansuri | 3 | 957 | binary search | 704 | 0.551 | Easy | 11,639 |
https://leetcode.com/problems/binary-search/discuss/381138/Two-Solutions-in-Python-3 | class Solution:
def search(self, n: List[int], t: int) -> int:
return (lambda x: x if n[x] == t else -1)(bisect.bisect_left(n,t,0,len(n)-1))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | binary-search | Two Solutions in Python 3 | junaidmansuri | 3 | 957 | binary search | 704 | 0.551 | Easy | 11,640 |
https://leetcode.com/problems/binary-search/discuss/1834289/2-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-98 | class Solution:
def search(self, nums: List[int], target: int) -> int:
try: return nums.index(target)
except: return -1 | binary-search | 2-Lines Python Solution || 80% Faster || Memory less than 98% | Taha-C | 2 | 163 | binary search | 704 | 0.551 | Easy | 11,641 |
https://leetcode.com/problems/binary-search/discuss/1834289/2-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-98 | class Solution:
def search(self, nums: List[int], target: int) -> int:
return (lambda x: x if nums[x]==target else -1)(bisect_left(nums,target,0,len(nums)-1)) | binary-search | 2-Lines Python Solution || 80% Faster || Memory less than 98% | Taha-C | 2 | 163 | binary search | 704 | 0.551 | Easy | 11,642 |
https://leetcode.com/problems/binary-search/discuss/1834289/2-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-98 | class Solution:
def search(self, nums: List[int], target: int) -> int:
start=0 ; end=len(nums)-1
while start<=end:
mid=(start+end)//2
if nums[mid]<target: start=mid+1
elif nums[mid]>target: end=mid-1
else: return mid
return -1 | binary-search | 2-Lines Python Solution || 80% Faster || Memory less than 98% | Taha-C | 2 | 163 | binary search | 704 | 0.551 | Easy | 11,643 |
https://leetcode.com/problems/binary-search/discuss/1740276/Python3-or-Binary-search-or | class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
while start<=end:
mid = (end + start) // 2
if nums[mid] == target:
return mid
elif nums[mid]>target:
end =mid - 1
else:
start=mid + 1
return -1 | binary-search | β Python3 | Binary search | | Anilchouhan181 | 2 | 208 | binary search | 704 | 0.551 | Easy | 11,644 |
https://leetcode.com/problems/binary-search/discuss/2410266/Python-Accurate-Iterative-Solution-oror-Documented | class Solution:
# Iterative approach
def search(self, nums: List[int], target: int) -> int:
low, high = 0, len(nums) - 1 # two pointers low to high
# Repeat until the pointers low and high meet each other
while low <= high:
mid = (low + high) // 2 # middle point - pivot
if target == nums[mid]:
return mid # if match, return mid index
elif target > nums[mid]:
low = mid + 1 # target is on the right side
else:
high = mid - 1 # target is on the left side
return -1 # if not found at all, return -1 | binary-search | [Python] Accurate Iterative Solution || Documented | Buntynara | 1 | 20 | binary search | 704 | 0.551 | Easy | 11,645 |
https://leetcode.com/problems/binary-search/discuss/2386829/Step-by-Step-Explanation-ororPython-oror-Simplest | class Solution:
def search(self, nums: List[int], target: int) -> int:
# Using the ITERATIVE APPROACH with O(logn)
'''
Step-by-step Binary Search Algorithm: We basically ignore half of the elements just after one comparison.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
4. Else (x is smaller) recur for the left half.
'''
# Two containers
low_value = 0 # Index of first element
high_value = len(nums) - 1 # Index of last element
while low_value <= high_value: # check if the βhigh_valueβ is higher than the βlow_valueβ
middle_value = (low_value + high_value)//2 # middle index of our list which will be the floor of the average of βhigh_valueβ plus βlow_valueβ
if nums[middle_value] == target: # check if the middle element and the target are equal
return middle_value # If they are equal, the position of the item will be returned
if target < nums[middle_value]: # check if the middle element is less than the item to be searched
high_value = middle_value - 1 # the new position will shift to the right once.
else: # check if the value of the last index is greater than or equal to the value of the first index
low_value = middle_value + 1 # the new position will shift to the left once
return -1 # If the target is not in the list, it will return a statement | binary-search | Step by Step Explanation ||Python || Simplest | harishmanjunatheswaran | 1 | 75 | binary search | 704 | 0.551 | Easy | 11,646 |
https://leetcode.com/problems/binary-search/discuss/2316273/Solution-(Faster-than-90-) | class Solution:
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums)-1
if nums[0] == target:
return (0)
elif nums[-1] == target:
return (high)
for i in range(len(nums)):
mid = (low + high)//2
if nums[mid] == target:
return (mid)
elif nums[mid] < target:
low = mid
elif nums[mid] > target:
high = mid
return -1 | binary-search | Solution (Faster than 90 %) | fiqbal997 | 1 | 64 | binary search | 704 | 0.551 | Easy | 11,647 |
https://leetcode.com/problems/binary-search/discuss/2099189/Python-Simple-Recursive-Solution | class Solution(object):
def search(self, nums, target,count=0):
length=len(nums)
half_len=length/2
test=nums[half_len]
if test == target:
return half_len+count
if length == 1:
return -1
if test > target:
return self.search(nums[0:half_len],target,count+0)
else:
return self.search(nums[half_len:],target,count+half_len) | binary-search | Python Simple Recursive Solution | NathanPaceydev | 1 | 213 | binary search | 704 | 0.551 | Easy | 11,648 |
https://leetcode.com/problems/binary-search/discuss/2097983/Python3-runtime%3A-244ms-94.43 | class Solution:
def search(self, nums: List[int], target: int) -> int:
# return self.binarySearchIterative(nums, target)
return self.binarySearchByRecursion(nums, target)
# O(log(n)) || O(1)
# runtime: 244ms 94.43%
def binarySearchIterative(self, array, target):
left, right = 0, len(array) - 1
while left <= right:
mid = (left+right) // 2
maybeNum = array[mid]
if maybeNum == target:
return mid
elif maybeNum > target:
right = mid - 1
else:
left = mid + 1
return -1
# O(logN) || O(n)
# runtime: 527ms 5.05%
def binarySearchByRecursion(self, array, target):
if not array:
return -1
return self.binarySearchHelper(array, target, 0, len(array) - 1)
def binarySearchHelper(self, array, target, left, right):
if right >= left:
mid = (left + right) // 2
element = array[mid]
if element == target:
return mid
elif element < target:
return self.binarySearchHelper(array, target, mid + 1, right)
else:
return self.binarySearchHelper(array, target, left, mid - 1)
else:
return -1 | binary-search | Python3 # runtime: 244ms 94.43% | arshergon | 1 | 181 | binary search | 704 | 0.551 | Easy | 11,649 |
https://leetcode.com/problems/binary-search/discuss/1633607/220-ms-faster-than-99.34 | class Solution:
def search(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target:
return i
elif nums[i] != target:
i = i + 1
return -1 | binary-search | 220 ms, faster than 99.34% | OAOrzz | 1 | 282 | binary search | 704 | 0.551 | Easy | 11,650 |
https://leetcode.com/problems/binary-search/discuss/1633607/220-ms-faster-than-99.34 | class Solution:
def search(self, nums: List[int], target: int) -> int:
L,R = 0, len(nums)-1
while L<=R:
mid = (L+R)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
R = mid -1
elif nums[mid]<target:
L = mid + 1
return -1 | binary-search | 220 ms, faster than 99.34% | OAOrzz | 1 | 282 | binary search | 704 | 0.551 | Easy | 11,651 |
https://leetcode.com/problems/binary-search/discuss/1633607/220-ms-faster-than-99.34 | class Solution:
def search(self, nums: List[int], target: int) -> int:
dic = {}
for key, value in enumerate(nums):
if target == value:
return key
dic[value] = key
return -1 | binary-search | 220 ms, faster than 99.34% | OAOrzz | 1 | 282 | binary search | 704 | 0.551 | Easy | 11,652 |
https://leetcode.com/problems/binary-search/discuss/2847133/Python-or-Binary-Search-Solution-or-O(nlogn) | class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums)-1
while start <= end:
mid = (start+end)//2
if nums[mid] == target:
return mid
if nums[mid] < target:
start = mid+1
else:
end = mid-1
return -1 | binary-search | Python | Binary Search Solution | O(nlogn) | ajay_gc | 0 | 1 | binary search | 704 | 0.551 | Easy | 11,653 |
https://leetcode.com/problems/binary-search/discuss/2837333/simple-standard-template | class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums)-1
while l<=r:
mid = (l+r)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
l = mid+1
else:
r = mid-1
return -1 | binary-search | simple standard template | ajayedupuganti18 | 0 | 2 | binary search | 704 | 0.551 | Easy | 11,654 |
https://leetcode.com/problems/binary-search/discuss/2834704/Python-My-recursive-O(logn)-solution | class Solution:
def perform_search(self, nums: List[int], target: int, index: int) -> int:
if not nums:
return -1
if target == nums[index]:
return index
# if < target - left sublist
if target < nums[index]:
nums_sublist = nums[:index]
sub_index = self.perform_search(nums_sublist, target, len(nums_sublist)//2)
return index - (len(nums_sublist) - sub_index) if sub_index != -1 else -1
# if > target - right sublist
else:
nums_sublist = nums[index+1:]
sub_index = self.perform_search(nums_sublist, target, len(nums_sublist)//2)
return index + (sub_index + 1) if sub_index != -1 else -1
def search(self, nums: List[int], target: int) -> int:
return self.perform_search(nums, target, len(nums)//2) | binary-search | [Python] My recursive O(logn) solution | manytenks | 0 | 1 | binary search | 704 | 0.551 | Easy | 11,655 |
https://leetcode.com/problems/binary-search/discuss/2830321/Relatively-standard-python-binary-search | class Solution:
def search(self, nums: List[int], target: int) -> int:
def contains(elements: List[int], value: int, left: int, right: int) -> tuple[bool, int]:
# print(f'contains: {len(elements)=} {left=} {right=}')
if left <= right:
middle = left + (right - left) // 2
if elements[middle] == value:
return True, middle
if elements[middle] < value:
return contains(elements, value, middle + 1, right)
elif elements[middle] > value:
return contains(elements, value, left, middle - 1)
return False, -1
bool_contains, idx = contains(nums, target, 0, len(nums)-1)
return idx | binary-search | Relatively standard python binary search | sean2469 | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,656 |
https://leetcode.com/problems/binary-search/discuss/2829187/only-check-smaller-nums | class Solution:
def search(self, nums: List[int], target: int) -> int:
pointer = 0
while target >= nums[pointer]:
if target == nums[pointer]:return pointer
elif pointer < len(nums)-1: pointer += 1
else: break
return -1 | binary-search | only check smaller nums | roger880327 | 0 | 2 | binary search | 704 | 0.551 | Easy | 11,657 |
https://leetcode.com/problems/binary-search/discuss/2827292/binary-searcha | class Solution:
import math
def search(self, nums: List[int], target: int) -> int:
count = math.log(len(nums), 2)
count1 = int(count) + 1
min1 = 0
max1 = len(nums) - 1
for i in range(count1):
a = (max1 + min1) // 2
if nums[a] == target:
return a
elif nums[a] > target:
max1 = a - 1
elif nums[a] < target:
min1 = a + 1
return -1 | binary-search | binary searcha | cslab0001 | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,658 |
https://leetcode.com/problems/binary-search/discuss/2825941/Simple-Python-Solution | class Solution:
def search(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i]==target:
return i
return -1 | binary-search | Simple Python Solution | durgaraopolamarasetti | 0 | 4 | binary search | 704 | 0.551 | Easy | 11,659 |
https://leetcode.com/problems/binary-search/discuss/2817455/Binary-search | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
right = mid-1
else:
left = mid+1
return -1 | binary-search | Binary search | mohansai1443 | 0 | 5 | binary search | 704 | 0.551 | Easy | 11,660 |
https://leetcode.com/problems/binary-search/discuss/2817307/Binary-Search-or-Simple-Python | class Solution:
def search(self, nums: List[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
elif nums[mid] > target:
high = mid - 1
return -1 | binary-search | Binary Search | Simple Python | jaisalShah | 0 | 5 | binary search | 704 | 0.551 | Easy | 11,661 |
https://leetcode.com/problems/binary-search/discuss/2801272/binary-search_leetcode_704 | class Solution:
def search(self, nums: List[int], target: int) -> int:
return self.recursive_search(nums, 0, len(nums) - 1, target)
def recursive_search(self, nums, left, right, target):
if left > right:
return -1
mid = (left + right) // 2
if target < nums[mid]:
return self.recursive_search(nums, left, mid - 1, target)
if target > nums[mid]:
return self.recursive_search(nums, mid + 1, right, target)
return mid | binary-search | binary search_leetcode_704 | bsmrstujoycse | 0 | 1 | binary search | 704 | 0.551 | Easy | 11,662 |
https://leetcode.com/problems/binary-search/discuss/2795657/4-lines-Easy-to-understand-solution.-Using-Basic-Python. | class Solution:
def search(self, nums: List[int], target: int) -> int:
if(target in nums):
return nums.index(target)
else:
return -1 | binary-search | 4 lines, Easy to understand solution. Using Basic Python. | amartyadebdas | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,663 |
https://leetcode.com/problems/binary-search/discuss/2793462/Python-3-%3A-Using-Top-Down-DP | class Solution:
def search(self, nums: List[int], target: int, L : int=0) -> int:
# Using Top-Down DP
# Time Complexity : O(logN)
if target > nums[-1] or target < nums[0]: return -1
n: int = len(nums)
mid: int = n // 2
if nums[mid] == target:
return L + mid
elif nums[mid] < target:
nums = nums[mid:]
L += mid
else:
nums = nums[:mid]
return self.search(nums, target, L) | binary-search | Python 3 : Using Top-Down DP | boming05292 | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,664 |
https://leetcode.com/problems/binary-search/discuss/2792405/Python-and-Javascript-Solution | class Solution:
def search(self, nums: List[int], target: int) -> int:
lengthList = len(nums)
start = 0
end = lengthList - 1
while(start <= end):
mid = floor((start + end)/2)
if target > nums[mid]:
start = mid + 1
elif target < nums[mid]:
end = mid - 1
else:
return mid
return -1 | binary-search | Python and Javascript Solution | pnithinc | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,665 |
https://leetcode.com/problems/binary-search/discuss/2787159/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
l,r = 0,len(nums)-1
while l <= r:
m = ( l + r)//2
if nums[m] > target:
r = m - 1
elif nums[m] < target:
l = m + 1
else:
return m
return -1 | binary-search | Binary Search | khanismail_1 | 0 | 5 | binary search | 704 | 0.551 | Easy | 11,666 |
https://leetcode.com/problems/binary-search/discuss/2784768/Python-solution | class Solution(object):
def search(self, nums, target):
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) // 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
end = mid - 1
else:
start = mid + 1
return -1 | binary-search | Python solution | ochudi | 0 | 17 | binary search | 704 | 0.551 | Easy | 11,667 |
https://leetcode.com/problems/binary-search/discuss/2781879/Simple-python-solution | class Solution:
def search(self, nums: List[int], target: int) -> int:
try:
indx = nums.index(target)
return indx
except ValueError:
return -1 | binary-search | Simple python solution | fromJungle | 0 | 4 | binary search | 704 | 0.551 | Easy | 11,668 |
https://leetcode.com/problems/binary-search/discuss/2776633/Basic-Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums)-1
while l<=r:
mid = (l+r)//2
if nums[mid] == target:
return mid
elif nums[mid]<target:
l = mid+1
else:
r = mid-1
return -1 | binary-search | Basic Binary Search | pranayrishith16 | 0 | 6 | binary search | 704 | 0.551 | Easy | 11,669 |
https://leetcode.com/problems/binary-search/discuss/2746025/Python3-simple-solution-beats-96.99 | class Solution:
def search(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
return -1 | binary-search | Python3 simple solution - beats 96.99% | Ahmed1122 | 0 | 5 | binary search | 704 | 0.551 | Easy | 11,670 |
https://leetcode.com/problems/binary-search/discuss/2740320/Basic-Binary-Seach-by-Updating-Boundaries | class Solution:
def search(self, nums: List[int], target: int) -> int:
lhs = 0
rhs = len(nums)-1
while lhs <= rhs:
mid = (lhs+rhs)//2
if target > nums[mid]:
lhs = mid+1
elif target < nums[mid]:
rhs = mid-1
else:
return mid
return -1 | binary-search | Basic Binary Seach by Updating Boundaries | kookiejs | 0 | 2 | binary search | 704 | 0.551 | Easy | 11,671 |
https://leetcode.com/problems/binary-search/discuss/2740204/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
# use binary search to find the element
# use a low and high pointer to have search bounds
# calculate mid index by summing the bounds then
# getting the floor division of 2
# if the value is larger than the target, set high to the
# middle index - 1
# if the value is smaller than the target, set the low to
# the middle index + 1
# if the value is the target, return the index
# iterate while the left pointer doesn't become larger
# than the right
# if it does, return -1 after the loop
# time O(logn) space O(1)
l, h = 0, len(nums) - 1
while l <= h:
m = (l + h) // 2
if nums[m] == target:
return m
if nums[m] > target:
h = m - 1
if nums[m] < target:
l = m + 1
return -1 | binary-search | Binary Search | andrewnerdimo | 0 | 2 | binary search | 704 | 0.551 | Easy | 11,672 |
https://leetcode.com/problems/binary-search/discuss/2724020/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
#1.
# Make a while loop
# since array is already sorted, get the middle index
#
low = 0
up = len(nums)-1
while low <= up:
#Get the mid point of the array each iteration
mid = (low+up) // 2
#checks to see if mid point is equal to target
if nums[mid] == target:
return mid
#if num is greater than target it will move the up or righter pointer to the left
elif nums[mid] > target:
up = mid-1
#if num is less than target it will move the low or left pointer to the right
else:
low = mid+1
#if it iterates all the way through and does not find it, it will return -1
return -1 | binary-search | Binary Search | EverydayScriptkiddie | 0 | 4 | binary search | 704 | 0.551 | Easy | 11,673 |
https://leetcode.com/problems/binary-search/discuss/2723952/Binary-Search-at-O(log(n))-time-complexity | class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)
m = 0
while l < r - 1:
m = (l+r) >> 1
if nums[m] > target:
r = m
elif nums[m] < target:
l = m
else:
return m
if nums[0]==target:
return 0
return -1 | binary-search | Binary Search at O(log(n)) time complexity | Libo_Sun | 0 | 6 | binary search | 704 | 0.551 | Easy | 11,674 |
https://leetcode.com/problems/binary-search/discuss/2715416/Beginner-Friendly-and-Fast-Solution | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = (right + left) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1 | binary-search | Beginner Friendly and Fast Solution | user6770yv | 0 | 6 | binary search | 704 | 0.551 | Easy | 11,675 |
https://leetcode.com/problems/binary-search/discuss/2703406/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
# Binary Search
length = len(nums)
low = 0
high = length - 1
mid = 0
while low <= high:
mid = (low + high)//2
if (nums[mid] == target):
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid -1
return -1
# Basic Approach
"""
length = len(nums)
for index in range(length):
if nums[index] == target:
return index
return -1
""" | binary-search | Binary Search | jashii96 | 0 | 4 | binary search | 704 | 0.551 | Easy | 11,676 |
https://leetcode.com/problems/binary-search/discuss/2703372/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
length = len(nums)
for index in range(length):
if nums[index] == target:
return index
return -1 | binary-search | Binary Search | jashii96 | 0 | 4 | binary search | 704 | 0.551 | Easy | 11,677 |
https://leetcode.com/problems/binary-search/discuss/2690509/Binary-Search | class Solution:
def search(self, nums: List[int], target: int) -> int:
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] < target: i = m + 1
elif nums[m] > target:
j = m - 1
else:
return m
return -1 | binary-search | Binary Search | Erika_v | 0 | 2 | binary search | 704 | 0.551 | Easy | 11,678 |
https://leetcode.com/problems/binary-search/discuss/2667168/Binary-search-python | class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums) - 1
while l <= r:
m = l + (r-l)//2
if nums[m] == target:
return m
elif nums[m] > target:
r = m - 1
else:
l = m + 1
return -1 | binary-search | Binary search python | sahilkumar158 | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,679 |
https://leetcode.com/problems/binary-search/discuss/2657816/PYTHON-BINARY-SEARCH-SOLUTION | class Solution:
def search(self, nums: List[int], target: int) -> int:
for count, n in enumerate(nums):
if n == target:
return count
return -1 | binary-search | PYTHON BINARY SEARCH SOLUTION | ivanibhawoh | 0 | 6 | binary search | 704 | 0.551 | Easy | 11,680 |
https://leetcode.com/problems/binary-search/discuss/2651309/Binary-Search-Simple-Implementation | class Solution:
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums)-1
loc = -1
while (low <= high):
mid = (high+low)//2
if nums[mid] == target:
return mid
if nums[mid] > target:
high = mid-1
elif nums[mid] < target:
low = mid+1
return loc | binary-search | Binary Search Simple Implementation | karanjadaun22 | 0 | 3 | binary search | 704 | 0.551 | Easy | 11,681 |
https://leetcode.com/problems/design-hashset/discuss/1947672/Python3-Linked-List-Solution-(faster-than-83) | # Linked List Solution
class MyHashSet(object):
def __init__(self):
self.keyRange = 769
self.bucketArray = [LinkedList() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].append(key)
def remove(self, key):
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].deleteNodeKeyAll(key)
# while self.bucketArray[bucketIndex].search(key):
# self.bucketArray[bucketIndex].deleteNodeKeyOne(key)
def contains(self, key):
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].search(key)
# ---------------------------------------------------------
## Define a linked list
class Node:
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# ---------------------------------------------------------
## Insert a new node
### Insert the new node at the front of the linked list
def push(self, new_val):
new_node = Node(new_val)
new_node.next = self.head
self.head = new_node
### Insert the new node at the end of the linked list
def append(self, new_val):
new_node = Node(new_val)
if self.head is None:
self.head = new_node
return
# Traverse till the end of the linked list
last = self.head
while last.next:
last = last.next
last.next = new_node
### Insert the new node after a given node
def insertAfter(self, new_val, prev_node):
if prev_node is None:
print("Please enter the node which is the previous node of the inserted node.")
return
new_node = Node(new_val)
new_node.next = prev_node.next
prev_node.next = new_node
# ---------------------------------------------------------
## Delete a node
### Delete a node by value
# Iterative Method
def deleteNodeKeyOne(self, key): # delete a single node
temp = self.head
if temp is None:
return
if temp.val == key:
self.head = temp.next
temp = None
return
while temp is not None:
if temp.val == key:
break
prev = temp
temp = temp.next
if temp is None:
return
prev.next = temp.next
temp = None
def deleteNodeKeyAll(self, key): # delete all the nodes with value key
temp = self.head
if temp is None:
return
while temp.val == key:
deletedNode = temp
self.head = temp.next
temp = self.head
deletedNode = None
if temp is None:
return
nxt = temp.next
while nxt is not None:
if nxt.val == key:
deletedNode = nxt
temp.next = nxt.next
deletedNode = None
temp = nxt
nxt = nxt.next
### Delete a node by position and return the value of the deleted node
def deleteNodePosition(self, position):
if self.head is None:
return
if position == 0:
temp = self.head
self.head = self.head.next
temp = None
return
idx = 0
current = self.head
prev = self.head
nxt = self.head
while current is not None:
if idx == position:
nxt = current.next
break
prev = current
current = current.next
idx += 1
prev.next = nxt
current = None
# ---------------------------------------------------------
# Print a linked list
def printList(self):
temp = self.head
while temp:
print (" %d" %(temp.val))
temp = temp.next
# ---------------------------------------------------------
## Search an element in a linked list
def search(self, x):
current = self.head
while current is not None:
if current.val == x:
return True
current = current.next
return False | design-hashset | Python3 Linked List Solution (faster than 83%) | Mr_Watermelon | 0 | 105 | design hashset | 705 | 0.659 | Easy | 11,682 |
https://leetcode.com/problems/design-hashset/discuss/1947665/Python3-Array-List-Solution | # Array List Solution
class MyHashSet:
def __init__(self):
self.buckets = []
def add(self, key: int) -> None:
count = 0
for x in self.buckets:
if key in x:
x += [key]
count += 1
if count == 0:
self.buckets += [[key]]
def remove(self, key: int) -> None:
for x in self.buckets:
while key in x:
x.remove(key)
def contains(self, key: int) -> bool:
for x in self.buckets:
if key in x:
return True
return False | design-hashset | Python3 Array List Solution | Mr_Watermelon | 0 | 65 | design hashset | 705 | 0.659 | Easy | 11,683 |
https://leetcode.com/problems/to-lower-case/discuss/2411462/Python3-ToLowerCase-Explanation-using-ASCII | class Solution:
def toLowerCase(self, s: str) -> str:
# Instead of using .lower(), let's implement with ASCII
# ord() returns the ascii value of a passed character
# Uncomment the line below to see the ASCII value of some important characters
# print(ord('a'), ord('z'), ord('A'), ord('Z'))
# Notice 'a'=97, and 'A'=65
# This can be used to tell whether a character is upper/lower case, and can help us convert between them
# First, make the string a list so we can change each char individually
s = list(s)
# Then, loop through the characters, and if their ascii value is <= 90 and >= 65, they must be upper case
# Use the difference (97 - 65 = 32) to convert it from upper to lower, then use chr() to convert from ascii to char
# - ord('A') + 32 = 97 = ord('a')
for i in range(len(s)):
if ord(s[i]) <= 90 and ord(s[i]) >= 65:
s[i] = chr(ord(s[i])+32)
return ''.join(s) | to-lower-case | [Python3] ToLowerCase - Explanation - using ASCII | connorthecrowe | 2 | 84 | to lower case | 709 | 0.82 | Easy | 11,684 |
https://leetcode.com/problems/to-lower-case/discuss/1387579/Python-solution-using-ASCII | class Solution:
def toLowerCase(self, s: str) -> str:
res = ""
for i in s:
if ord(i) >= 65 and ord(i) <=90:
res+=chr(ord(i)+32)
else:
res+=i
return res | to-lower-case | Python solution using ASCII | shraddhapp | 2 | 189 | to lower case | 709 | 0.82 | Easy | 11,685 |
https://leetcode.com/problems/to-lower-case/discuss/2827629/One-Line-Code | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | One Line Code | patelhet050603 | 1 | 29 | to lower case | 709 | 0.82 | Easy | 11,686 |
https://leetcode.com/problems/to-lower-case/discuss/2300527/Simplest-one-line-code | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Simplest one line code | Akash2907 | 1 | 55 | to lower case | 709 | 0.82 | Easy | 11,687 |
https://leetcode.com/problems/to-lower-case/discuss/2163675/Python-Easy-One-Liner-Solution | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python Easy One Liner Solution | pruthashouche | 1 | 58 | to lower case | 709 | 0.82 | Easy | 11,688 |
https://leetcode.com/problems/to-lower-case/discuss/1852026/95-faster-and-67-less-memory-oror-Python | class Solution:
def toLowerCase(self, s: str) -> str:
ls = ''
for char in s:
if ord(char) > 64 and ord(char) < 91:
ls += chr(ord(char) + 32)
else:
ls += char
return ls | to-lower-case | 95% faster & 67% less memory || Python | kbkvamsi | 1 | 79 | to lower case | 709 | 0.82 | Easy | 11,689 |
https://leetcode.com/problems/to-lower-case/discuss/1227364/TO-LOWER-CASE-or-PYTHON-SOLN | class Solution(object):
def toLowerCase(self, s):
for i in range(len(s)):
if ord("A")<=ord(s[i])<=ord("Z"):
s=s[:i]+chr(ord(s[i])+32)+s[i+1:]
return s
``` | to-lower-case | TO LOWER CASE | PYTHON SOLN | aayush_chhabra | 1 | 56 | to lower case | 709 | 0.82 | Easy | 11,690 |
https://leetcode.com/problems/to-lower-case/discuss/2822069/Python-One-Liner | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python One-Liner | PranavBhatt | 0 | 2 | to lower case | 709 | 0.82 | Easy | 11,691 |
https://leetcode.com/problems/to-lower-case/discuss/2811682/python-one-liner-easiest | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | [python]--one liner\\ easiest | user9516zM | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,692 |
https://leetcode.com/problems/to-lower-case/discuss/2773278/Simple-Python-Solution | class Solution:
def toLowerCase(self, s: str) -> str:
list1 = []
str1 = ""
for i in s:
list1.append(i.lower())
for i in list1:
str1 = str1 + i
return str1 | to-lower-case | Simple Python Solution | dnvavinash | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,693 |
https://leetcode.com/problems/to-lower-case/discuss/2771974/Simple-Linear-Time-Python-Easy-Solution | class Solution(object):
def toLowerCase(self, s):
ans=['']*len(s) #we can only manipulate strings using lists
counter=0 #keeping track of the character we are traversing
for char in s:
currAscii=ord(char)
if currAscii>=65 and currAscii<=65+25: #if ascii of char is of a capital letter
currAscii=currAscii+32 #converting the ascii of larger char to smaller char
ans[counter]=chr(currAscii) #converting ascii back to letter
counter+=1 #incrementing idx for the char we will add in our list
return "".join(ans) #converting our list to string | to-lower-case | Simple Linear Time Python Easy Solution | fa19-bcs-016 | 0 | 5 | to lower case | 709 | 0.82 | Easy | 11,694 |
https://leetcode.com/problems/to-lower-case/discuss/2770374/python-1-liner | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | python 1 liner | user7798V | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,695 |
https://leetcode.com/problems/to-lower-case/discuss/2770192/Python3-Beginners-approach-using-ascii | class Solution:
def toLowerCase(self, s: str) -> str:
def lower(char):
return ord(char)
output = ''
for char in s:
if 65 <= lower(char) <= 90:
char = chr(ord(char) + 32)
output = output + char
return output | to-lower-case | Python3 Beginners approach using ascii | OGLearns | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,696 |
https://leetcode.com/problems/to-lower-case/discuss/2764413/Python-or-LeetCode-or-709.-To-Lower-Case | class Solution:
def toLowerCase(self, s: str) -> str:
return_str = ""
for e in s:
if "A" <= e <= "Z":
return_str += chr(ord(e) - ord("A") + ord("a"))
else:
return_str += e
return return_str | to-lower-case | Python | LeetCode | 709. To Lower Case | UzbekDasturchisiman | 0 | 5 | to lower case | 709 | 0.82 | Easy | 11,697 |
https://leetcode.com/problems/to-lower-case/discuss/2764413/Python-or-LeetCode-or-709.-To-Lower-Case | class Solution:
def toLowerCase(self, s: str) -> str:
return_str = ""
for e in s:
if "A" <= e <= "Z":
return_str += chr(ord(e) + 32)
else:
return_str += e
return return_str | to-lower-case | Python | LeetCode | 709. To Lower Case | UzbekDasturchisiman | 0 | 5 | to lower case | 709 | 0.82 | Easy | 11,698 |
https://leetcode.com/problems/to-lower-case/discuss/2764413/Python-or-LeetCode-or-709.-To-Lower-Case | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python | LeetCode | 709. To Lower Case | UzbekDasturchisiman | 0 | 5 | to lower case | 709 | 0.82 | Easy | 11,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.