🤖
Data Structures and Algorithms
  • CS Theory And Problems
  • Big O
    • Big O Notation
  • Algorithms
    • Binary Search
    • Breadth First Search (BFS)
    • Depth First Search (DFS)
    • Dynamic Programming
    • Kadane's Algorithm
    • Kahn's Algorithm
    • Quickselect
    • Recursion
    • Sorting Algorithms
    • Sliding Window
  • Data Structures
    • Binary Heap
    • Graph
    • Linked List
    • Trees
  • Problems
    • LeetCode
      • 1. Two Sum
      • 3. Longest Substring Without Repeating Characters
      • 5. Longest Palindromic Substring
      • 11. Container With Most Water
      • 15. 3 Sum
      • 19. Remove Nth Node From End of List
      • 20. Valid Parentheses
      • 33. Search in Rotated Sorted Array
      • 49. Group Anagrams
      • 53. Maximum Subarray
      • 55. Jump Game
      • 56. Merge Intervals
      • 76. Minimum Window Substring
      • 98. Validate Binary Search Tree
      • 105. Construct Binary Tree from Preorder and Inorder Traversal
      • 121. Best Time to Buy and Sell Stock
      • 133. Clone Graph
      • 141. Linked List Cycle
      • 152. Maximum Product Subarray
      • 153. Find Minimum in Rotated Sorted Array
      • 200. Number of Islands
      • 206. Reverse Linked List
      • 207. Course Schedule
      • 217. Contains Duplicate
      • 226. Invert Binary Tree
      • 238. Product of Array Except Self
      • 242. Valid Anagram
      • 297. Serialize and Deserialize Binary Tree
      • 347. Top K Frequent Elements
      • 417. Pacific Atlantic Water Flow
      • 424. Longest Repeating Character Replacement
      • 435. Non-overlapping Intervals
      • 647. Palindromic Substrings
Powered by GitBook
On this page
  • Iterative Algorithm
  • Recursive Algorithm
  • Resources
  1. Algorithms

Binary Search

Use on a sorted collection to discard half of the collection with each iteration. This narrows the collection down to the target value if one exists. If the loop runs to completion then the target value is not in the collection.

Time complexity: O(log n)

Space complexity: O(1) for iterative algorithm. O(log n) for recursive algorithm.

Iterative Algorithm

def binary_search(nums: List[int], target: [int]) -> int | None:
    left = 0
    right = len(nums) - 1
    # Less than or equal check is used in while condition to handle the case when there is one element
    while left <= right:
        # the middle (or average) of the range
        mid = (right + left) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return None

Note:

  • The mid = (right + left) // 2 formula is fine for Python, where we don't need to worry about Integer overflow errors. In Java the formula should be mid = left + (right - left) / 2. See Integer Overflow error in this article.

Recursive Algorithm

def binary_search_recursive(nums: List[int], target: [int]) -> int | None:
    def recursive(left, right):
        if left > right:
            return None
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            return recursive(mid + 1, right)
        else:
            return recursive(left, mid - 1)

    return recursive(0, len(nums) - 1)

Resources

https://realpython.com/binary-search-python/

PreviousBig O NotationNextBreadth First Search (BFS)

Last updated 3 years ago