Binary Search

Binary Search
Easy

Approach

Diagrams

Analysis

Time

O(log(n))

Space

O(1)
class Solution:
    def search(self, nums, target):
        leftIdx = 0
        rightIdx = len(nums) - 1

        while leftIdx <= rightIdx:
            midIdx = (leftIdx + rightIdx) // 2
            mid = nums[midIdx]
            
            if target == mid:
                return midIdx

            if target > mid:
                leftIdx = midIdx + 1

            else:
                rightIdx = midIdx - 1

        return -1

Learn

#Binary Search

Videos