AlgoInsight

DSA problem

Binary Search

EasyBinary SearchPattern: Binary Searchtop75AmazonGoogleMicrosoftAppleBloomberg

Given a sorted array of integers nums (in ascending order) and an integer target, return the index of target in the array. If target does not exist, return -1.

You must write an algorithm with O(log n) runtime complexity. That hard upper bound is the whole point of the problem: a linear scan, while correct, defeats the purpose of starting from a sorted input. The intent is to internalize the canonical bisection idea that underlies dozens of harder problems later on.

The classical approach maintains two pointers lo and hi that bracket the still-possible range of indices. On each iteration compute mid = lo + (hi - lo) / 2 — note the subtraction form, which prevents integer overflow when lo + hi could exceed the type's maximum value. Compare nums[mid] to target: equal means done, less means the answer is strictly to the right (lo = mid + 1), greater means strictly to the left (hi = mid - 1).

A correct binary search hinges on getting the loop invariant right and on terminating. With inclusive bounds (hi = n - 1) the loop condition is lo <= hi; each iteration always shrinks the search window by at least one because mid is excluded by the +1 / -1 updates. The result is O(log n) time and O(1) space, with no recursion stack overhead.

Examples

Example 1
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 sits at index 4. Starting with lo=0, hi=5, the mid value 3 is too small so lo moves to 3; next mid is 4 where nums[4] = 9, returning 4.
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 is not present. The search ends with lo > hi after the window shrinks to nothing, so the function returns -1.
Example 3
Input: nums = [5], target = 5
Output: 0
Explanation: A single-element array is the simplest case: mid = 0 matches the target immediately.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharray

Browse all DSA problems