Binary Search
Find the index of a target value in a sorted ascending array in O(log n) time by halving the search range each step.
01The 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.
| Input | Output | Why |
|---|---|---|
nums = [-1, 0, 3, 5, 9, 12], target = 9 | 4 | 9 exists at index 4 |
nums = [-1, 0, 3, 5, 9, 12], target = 2 | -1 | 2 does not exist in nums |
nums = [5], target = 5 | 0 | Single element match |
nums = [5], target = -5 | -1 | Single element miss |
Constraints: 1 to 10,000 elements, sorted ascending with distinct integers.
02How to spot it
- The input array is sorted in ascending order.
- The runtime constraint explicitly demands O(log n) time.
- Comparing against the middle element allows half of the remaining array to be discarded immediately.
So: classic binary search on a closed range [lo, hi].
03Pseudocode
lo = 0 ; hi = n - 1
while lo <= hi:
mid = lo + (hi - lo) / 2
if a[mid] == target: return mid
if a[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1- Look at the middle element
mid. - Target is bigger? Discard the left half:
lo = mid + 1. - Target is smaller? Discard the right half:
hi = mid - 1. If equal, returnmid.
04Watch it work
Start search for target 9 across full range [0 .. 5].
Pseudocode
- lo = 0 ; hi = n - 1
- while lo <= hi:
- mid = lo + (hi - lo) / 2
- if a[mid] == target: return mid
- if a[mid] < target: lo = mid + 1
- else: hi = mid - 1
- return -1
Variables
- lo
- 0
- hi
- 5
- target
- 9
05Step-by-step dry run
- 1-1001325394125lohi
Start search for target 9 across full range [0 .. 5].
lo = 0hi = 5target = 9
- 2-1001325394125lomidhi
Calculate middle index: mid = 2 (value = 3).
lo = 0hi = 5mid = 2value = 3target = 9
- 3-1001325394125lohi
a[2] (3) < target (9). Target must be in right half: set lo = 3.
lo = 3hi = 5target = 9
- 4-1001325394125lomidhi
Calculate middle index: mid = 4 (value = 9).
lo = 3hi = 5mid = 4value = 9target = 9
- 5-1001325394125lomidhi
a[4] equals target 9! Found match at index 4.
mid = 4result = 4
06Java solution
public class BinarySearch {
public static int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // prevent integer overflow
if (nums[mid] == target) return mid;
if (nums[mid] < target) lo = mid + 1; // target is to the right
else hi = mid - 1; // target is to the left
}
return -1;
}
public static void main(String[] args) {
System.out.println(search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
System.out.println(search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
System.out.println(search(new int[]{5}, 5));
System.out.println(search(new int[]{5}, -5));
}
}4 -1 0 -1
Tricky lines, decoded
lo + (hi - lo) / 2: Prevents 32-bit integer overflow. Writing(lo + hi) / 2can exceedInteger.MAX_VALUEwhen both bounds are large.while (lo <= hi): Uses<=because a range containing exactly one element (lo == hi) must still be inspected.
07Why it works
Because nums is sorted in ascending order, every element to the left of mid is smaller than or equal to nums[mid], and every element to the right is greater than or equal to nums[mid]. Comparing target to nums[mid] determines with certainty which half cannot hold target. Discarding that half leaves target (if present) strictly inside [lo, hi]. The candidate range halves on every iteration, terminating in at most log₂ n steps.
Invariant: If target exists in nums, its index lies within the closed interval [lo, hi].
08Time and space
- Time: O(log n). An array of 10,000 elements requires at most 14 comparisons.
- Space: O(1). Only three integer variables (
lo,mid,hi) are tracked.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
[5], target = 5 | 0 | Single element, found |
[5], target = -5 | -1 | Single element, absent |
[1, 3], target = 3 | 1 | Target is at the very end |
[1, 3], target = 1 | 0 | Target is at the very beginning |
[-1, 0, 3, 5], target = 2 | -1 | Target belongs between two adjacent values |
10Common mistakes
- Integer overflow with
(lo + hi) / 2. Whenlo + hiexceeds 2³¹ − 1, the sum overflows to a negative number. Always writelo + (hi - lo) / 2. - Using
while (lo < hi)withhi = mid - 1. This loop terminates prematurely when only one element remains, skipping the check for single-element arrays or the boundary element. - Writing
lo = midorhi = mid. In the exact-match template with integer division rounding down,lo = midwhenhi = lo + 1causes an infinite loop. Always usemid + 1andmid - 1.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Linear scan | O(n) | O(1) | Unsorted arrays only |
| Binary search | O(log n) | O(1) | Default interview solution |
Arrays.binarySearch | O(log n) | O(1) | Production code; returns negative on miss |
| Recursive search | O(log n) | O(log n) | Recursion demonstration, uses stack memory |
12In the interview
- Duplicates present? Classic binary search finds an arbitrary matching copy. Use lower bound or upper bound searches (Problem 39) to find the first or last occurrence.
- Array of unknown or infinite size? Start with
hi = 1, and repeatedly doublehi *= 2untilnums[hi] >= target. Then binary search in[hi / 2, hi]in O(log n) time.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why is lo + (hi - lo) / 2 preferred over (lo + hi) / 2 in binary search?
2. What happens in classic binary search if you write while (lo < hi) instead of while (lo <= hi)?
14Solve it yourself
Try it on LeetCode #704.