< Back




704. Binary Search

Standard binary search.

The solution is as follows:


  class Solution:
      def search(self, nums: List[int], target: int) -> int:
          l = 0
          r = len(nums) - 1

          while l <= r:
              m = (l + r) // 2

              if nums[m] == target:
                  return m
              elif nums[m] < target:
                  l = m + 1
              else:
                  r = m - 1

          return -1


_ Time Complexity:

  O(log(n)) - Standard binary search time complexity.

_ Space Complexity:

  O(1) - Binary search uses constant space.