Binary Search
Pattern: Binary search on sorted arrays
The classic search on a sorted array. Look at the middle, keep the half that can still hold the target, and stop when you find it or the range is empty.
The problem
You are given an array of different whole numbers sorted in increasing order, and a target. Return the index of the
target, or -1 if it is not there. The search must take O(log n) time. For example, [-1, 0, 3, 5, 9, 12] with target 9
gives 4, and with target 2 gives -1.
The function name search matches LeetCode. Use the link above for the exact statement and limits.
Think first
- After you look at one middle value, which half can you rule out?
- What do
loandhimean, and when is the range empty? - How many looks does a range of 1,000,000 values take?
Hints
Brute force, and why it fails
Check every index from left to right: O(n). That ignores the sorting. Halving the range each time takes about
log₂ n steps, which is 20 for a million values.
The key insight
In a sorted array, one comparison with the middle value rules out half of the range, because everything on one side is smaller and everything on the other is bigger.
Dry run
nums = [-1, 0, 3, 5, 9, 12] and target = 9. The target, if present, is somewhere in lo..hi.
The plan
lo = 0, hi = n - 1
while lo <= hi:
mid = lo + (hi - lo) / 2
if nums[mid] == target: return mid
if nums[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
Complexity
- Time
O(log n)- Space
O(1)
The range halves each step, and only three indexes are stored.
Edge cases
- One value: either it is the target or the answer is -1.
- Target smaller than everything or bigger than everything:
hiorlowalks off one end and the loop stops. - Two values: check both positions and a missing target.
I've built my logic, show the code
Java
class Solution {
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1; // the answer, if any, is inside nums[lo..hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // avoids overflow of lo + hi
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;
}
}C++
class Solution {
public:
int search(vector<int>& nums, int target) {
int lo = 0, hi = static_cast<int>(nums.size()) - 1; // the answer, if any, is inside nums[lo..hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // avoids overflow of lo + hi
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;
}
};Python
class Solution:
def search(self, nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1 # the answer, if any, is inside nums[lo..hi]
while lo <= hi:
mid = (lo + hi) // 2
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 -1Common mistakes
- Looping while
lo < hi, which never checks the last remaining value. - Setting
lo = midorhi = mid, which can loop forever when two values are left. - Computing
(lo + hi) / 2in Java or C++, which can overflow for very large arrays.