Binary Search (LeetCode 704): Solution and Explanation
Given a sorted array of distinct integers and a target value, return the index of the target, or -1 if it is not present. The solution must run in logarithmic time.
Watch it run step by step
Try your own input and write the code →Intuition
A linear scan checks each element in turn and takes O(n) time. It ignores the most useful fact you have: the array is sorted. If you look at any element and it is larger than the target, then every element to its right is larger too, so none of them can be the answer. One comparison eliminates a whole side of the array.
Binary search makes that elimination as aggressive as possible by always comparing against the middle of the range that is still possible. Whatever the result, half of the remaining candidates are thrown away. Starting from n elements, after one step you have about n/2, then n/4, and after about log₂ n steps only one candidate or none remains. For a million elements that is around 20 comparisons instead of a million.
The cleanest way to get the details right is to hold a loop invariant. In this version, the target, if it exists, is always somewhere in the closed range [l, r]. The loop runs while that range is non-empty, which means l <= r. If nums[m] is too big, the target must be in [l, m - 1], so set r = m - 1. If it is too small, the target is in [m + 1, r], so set l = m + 1. Because m itself has been ruled out each time, the range always shrinks, and the loop cannot get stuck.
Approach: Iterative binary search on a closed interval
- Set
l = 0andr = len(nums) - 1so the search range covers the whole array. - While
l <= r, compute the middle indexm = (l + r) // 2. - If
nums[m] > target, the target can only be left ofm, so setr = m - 1. - If
nums[m] < target, the target can only be right ofm, so setl = m + 1. - Otherwise
nums[m]equals the target, so returnm. - If the loop ends because
l > r, the range is empty and the target is absent, so return -1.
Step-by-step example
nums = [-1, 0, 3, 5, 9, 12], target = 9
- l = 0, r = 5, m = 2. nums[2] = 3 is less than 9, so l = 3.
- l = 3, r = 5, m = 4. nums[4] = 9 equals the target, so return 4.
- For target = 2 instead: m = 2 gives 3 > 2 so r = 1; m = 0 gives -1 < 2 so l = 1; m = 1 gives 0 < 2 so l = 2. Now l > r and the function returns -1.
Code: Python, Java, C++
1class Solution:
2 def search(self, nums: List[int], target: int) -> int:
3 l, r = 0, len(nums) - 1
4
5 while l <= r:
6 m = (l + r) // 2
7 if nums[m] > target:
8 r = m - 1
9 elif nums[m] < target:
10 l = m + 1
11 else:
12 return m
13 return -11class Solution {
2 public int search(int[] nums, int target) {
3 int l = 0;
4 int r = nums.length - 1;
5
6 while (l <= r) {
7 int m = l + (r - l) / 2;
8 if (nums[m] > target) {
9 r = m - 1;
10 } else if (nums[m] < target) {
11 l = m + 1;
12 } else {
13 return m;
14 }
15 }
16 return -1;
17 }
18}1class Solution {
2public:
3 int search(vector<int>& nums, int target) {
4 int l = 0;
5 int r = nums.size() - 1;
6
7 while (l <= r) {
8 int m = l + (r - l) / 2;
9 if (nums[m] > target) {
10 r = m - 1;
11 } else if (nums[m] < target) {
12 l = m + 1;
13 } else {
14 return m;
15 }
16 }
17 return -1;
18 }
19};Time and space complexity
O(log n)
Each iteration halves the size of the range [l, r], so the loop runs at most about log₂ n + 1 times.
O(1)
The iterative version uses only the three indices l, r and m.
Other approaches
Recursive binary search (time O(log n), space O(log n))
Pass l and r as parameters and recurse into the half that can still contain the target. The logic is the same but each level adds a stack frame.
Library bisect (time O(log n), space O(1))
Python's bisect_left returns the insertion point for the target in O(log n); checking whether that index holds the target gives the answer. It is concise but interviewers usually want the loop written out.
Common mistakes
- Writing
while l < rwith this closed-interval version. When the range shrinks to a single element, the loop exits without checking it, so a target at that position is reported missing. - Setting
r = morl = minstead ofm - 1andm + 1. Whenlandrare adjacent,mcan stay the same and the loop never ends. - Computing the middle as
(l + r) / 2with 32-bit ints in Java or C++ on huge arrays. The sum can overflow;l + (r - l) / 2avoids it. Python integers do not overflow. - Running binary search on unsorted data. The halving argument depends entirely on sorted order.
Frequently asked questions
Why is binary search O(log n)?
Each comparison discards half of the remaining candidates. Starting from n, the range can be halved only about log₂ n times before it is empty.
Should the loop be l <= r or l < r?
It depends on the interval convention. With a closed range [l, r] and updates m - 1 and m + 1, use l <= r. With a half-open range [l, r), use l < r and set r = m.
How do you avoid integer overflow in binary search?
Compute the midpoint as l + (r - l) / 2 instead of (l + r) / 2. That matters in languages with fixed-width integers such as Java and C++.
What if the array has duplicates?
This version returns some index of the target but not necessarily the first or last one. To get a boundary, keep searching left or right after a match instead of returning.