Binary Search
Easy
Topics
Given a sorted (ascending) array nums of distinct integers and a target, return its index, or -1 if not present. Must run in O(log n).
Example 1
The values are sorted ascending, and the answer is the index of 9 rather than the value itself. It sits at index 4.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4
Example 2
It does not appear, and a missing target answers
-1.Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1
Constraints
- 1 <= nums.length <= 10^4
- nums is sorted ascending with distinct values.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A sorted array lets one comparison eliminate half the remaining candidates: compare the target to the middle and recurse into the half that could contain it.
Approach
- Keep an inclusive window
[lo, hi]. - Compute
mid; if it equals the target, return it. - If the middle value is smaller, search the right half; otherwise the left half.
- An empty window means the target is absent → return -1.
Walkthrough
nums = [-1,0,3,5,9,12], target = 9
lo=0 hi=5 mid=2 (3) < 9 -> lo=3
lo=3 hi=5 mid=4 (9) == 9 -> return 4Complexity
- Time — O(log n): the search range halves each iteration.
- Space — O(1): iterative with two indices.
Common Pitfalls
- In languages with fixed-width ints, use
lo + (hi - lo) // 2to avoid overflow. - Use
lo <= hi(inclusive) to not miss the last element.
Full Solution — all languages
class Solution:
def search(self, nums, target):
lo, hi = 0, len(nums) - 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 -1import java.util.*;
class Solution {
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int search(vector<int>& nums, int target) {
int lo = 0, hi = (int)nums.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var search = function(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
};
Asked at
Cognizant