Binary Search — LeetCode 704 Python Solution

EasyArrayBinary Search
Problem
#704
Reading time
2 min

The problem

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index.

Example

Input
nums = [-1,0,3,5,9,12], target = 9
Output
4
Explanation
9 exists in nums and its index is 4

Python solution

Python
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums) - 1
        while l < r:
            mid = (l + r) >> 1
            if nums[mid] >= target:
                r = mid
            else:
                l = mid + 1
        return l if nums[l] == target else -1

Complexity

MeasureComplexity
TimeO(\log n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 704. Binary Search is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Grind 75.

Frequently asked questions

How hard is LeetCode 704. Binary Search?
LeetCode 704. Binary Search is rated Easy on LeetCode.
What is the time complexity of LeetCode 704. Binary Search?
The Python solution on this page runs in O(\log n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 704. Binary Search?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 704. Binary Search cover?
LeetCode 704. Binary Search is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview