AAlgoLoopSpaced repetition for LeetCode
EASYBinary SearchLeetCode ↗

Binary Search

The key idea

Because nums is sorted, one comparison against the middle element tells you which half can possibly contain target. Discard the other half and repeat, halving the search space each step — that is what gives O(log n).

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. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

The values in nums are distinct, so target can match at most one index.

Constraints

Examples

Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4
Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems