DSA Visualizer · 25 visualizationsBinary Search
Binary Search
Given an array of integers nums sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise, return -1.
Point lo at the first cell and hi at the last. The answer, if it exists, sits somewhere inside this window.
Problem
Given an array of integers nums sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Examples
9 exists at index 4
2 does not exist
Constraints
- 1 ≤ nums.length ≤ 10⁴
- All integers are unique
- nums is sorted ascending
Intuition
Because the array is sorted, comparing the target with the middle element tells us which half the target must be in. Discard the other half and repeat on what remains — the window halves every step, so we need about log₂ n comparisons.
Brute force → Optimal
Walk every element from left to right and return the index where it equals the target; return -1 if the scan ends.
Keep a window [lo, hi]. Look at mid = (lo + hi) / 2. If nums[mid] is the target, return mid; if it is smaller, the answer is to the right, so lo = mid + 1; otherwise hi = mid - 1. Stop when lo > hi.
Complexity
Edge cases
- Target smaller than the first element or larger than the last: the window collapses after a few halvings and the loop returns -1.
- A single-element array: the only middle is index 0, so the target is found immediately or not at all.
Common mistakes
- Using `while (lo < hi)` instead of `while (lo <= hi)`, which skips the final one-element window and can miss the target.
- Setting lo = mid instead of lo = mid + 1 when nums[mid] is too small, which can loop forever on a two-element window.