Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array nums sorted in increasing order, with no repeated values, and a number target. Return the index of target in nums, or -1 if it isn't there. The catch: your solution must run in O(log n) time.
Sizes: up to 10⁴ numbers, values between −10⁴ and 10⁴.
Example: nums = [-1, 0, 3, 5, 9, 12], target = 9 → 4, because nums[4] = 9. With target = 2 the answer is -1.
Start with brute force
Walk the array from left to right and return the first index where nums[i] == target. It's obviously correct and takes O(n) time.
For 10⁴ numbers that's fast enough on a computer, but it ignores the one thing the problem gave you: the array is sorted. The problem asks for O(log n) because that's about 14 steps for 10⁴ numbers instead of 10⁴. And the same idea will later search a range of 10⁹ possible answers in 30 steps, where a scan is hopeless.
Building the intuition
Think about how you find a word in a paper dictionary. You don't read page 1, then page 2. You open somewhere in the middle, see "M", and know your word "cat" is in the left half. One look threw away half the book.
Try it on the example. Look at the middle, nums[3] = 5. The target is 9. Since the array is sorted, everything at index 3 or before is at most 5, so the target can't be there. Half gone.
Now make that precise. Ask, for each index, the yes/no question "is nums[i] >= target?" For target = 9:
| i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| nums[i] | −1 | 0 | 3 | 5 | 9 | 12 |
| nums[i] >= 9? | F | F | F | F | T | T |
Because the array is sorted, the answers are always a run of falses followed by a run of trues. If the target exists, it sits exactly at the first T. If it doesn't, the first T holds a bigger number, or there is no T at all. So the problem becomes: find the first T. That's exactly what the template from the primer does.
The optimal approach
- Set
lo = 0andhi = n. Indexnis past the end; treat it as a "true" slot that means "every element is smaller than the target". - While
lo < hi:mid = lo + (hi - lo) // 2.- If
nums[mid] >= target, the first T is atmidor to its left:hi = mid. - Otherwise,
midand everything left of it are too small:lo = mid + 1.
- Now
lo == hiis the first index withnums[lo] >= target, the lower bound. - If
lo < nandnums[lo] == target, returnlo. Otherwise return-1.
The subtle detail: step 4 needs both checks. If the target is bigger than everything, the loop ends at lo = n, and reading nums[n] crashes, so test lo < n first. If the target falls between two values, lo points at the next bigger number, so test nums[lo] == target too.
You may have seen another version that uses while lo <= hi and returns as soon as nums[mid] == target. It works here, but it can't find the first of several equal values, and it's a second loop to keep straight. This stage uses one loop everywhere.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def search(self, nums: List[int], target: int) -> int:
# Find the first index with nums[i] >= target (the lower bound).
# Invariant: that index is always inside [lo, hi]; hi = n means "past the end".
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] >= target:
hi = mid # mid might be the answer, so keep it
else:
lo = mid + 1 # mid and everything left of it are too small
# lo is where target would sit; it's only a match if it's really there
if lo < len(nums) and nums[lo] == target:
return lo
return -1class Solution {
public:
int search(vector<int>& nums, int target) {
// Find the first index with nums[i] >= target (the lower bound).
// Invariant: that index is always inside [lo, hi]; hi = n means "past the end".
int lo = 0, hi = (int)nums.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // never overflows, and always < hi
if (nums[mid] >= target) {
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything left of it are too small
}
}
// lo is where target would sit; it's only a match if it's really there
if (lo < (int)nums.size() && nums[lo] == target) return lo;
return -1;
}
};class Solution {
public int search(int[] nums, int target) {
// Find the first index with nums[i] >= target (the lower bound).
// Invariant: that index is always inside [lo, hi]; hi = n means "past the end".
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // never overflows, and always < hi
if (nums[mid] >= target) {
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything left of it are too small
}
}
// lo is where target would sit; it's only a match if it's really there
if (lo < nums.length && nums[lo] == target) return lo;
return -1;
}
}/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
// Find the first index with nums[i] >= target (the lower bound).
// Invariant: that index is always inside [lo, hi]; hi = n means "past the end".
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] >= target) {
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything left of it are too small
}
}
// lo is where target would sit; it's only a match if it's really there
if (lo < nums.length && nums[lo] === target) return lo;
return -1;
};Dry run
nums = [-1, 0, 3, 5, 9, 12], target = 9, so n = 6:
| lo | mid | hi | nums[mid] | nums[mid] >= 9? | update |
|---|---|---|---|---|---|
| 0 | 3 | 6 | 5 | No | lo = 4 |
| 4 | 5 | 6 | 12 | Yes | hi = 5 |
| 4 | 4 | 5 | 9 | Yes | hi = 4 |
| 4 | 4 | stop |
lo = 4, which is inside the array, and nums[4] = 9. Return 4.
Now target = 2:
| lo | mid | hi | nums[mid] | nums[mid] >= 2? | update |
|---|---|---|---|---|---|
| 0 | 3 | 6 | 5 | Yes | hi = 3 |
| 0 | 1 | 3 | 0 | No | lo = 2 |
| 2 | 2 | 3 | 3 | Yes | hi = 2 |
| 2 | 2 | stop |
lo = 2, but nums[2] = 3, not 2. Return -1. Notice the loop didn't stop early at the third row, even though nums[mid] = 3 was "close". It always runs until lo == hi.
Complexity
- Time: O(log n). Every step at least halves the size of
[lo, hi]. Starting fromn + 1candidates, that's about log₂ n steps: 14 for 10⁴. - Space: O(1). Three integers, no matter how big the array is.
Edge cases and traps
- Target bigger than every element. The loop ends at
lo = n. Checklo < nbefore readingnums[lo]. - Target smaller than every element. The loop ends at
lo = 0, andnums[0]is bigger than the target, so the equality check returns-1. - One element.
lo = 0,hi = 1: one step, then the check. Works with no special case. hi = mid - 1whennums[mid] >= target. That throws awaymid, which may be the target. With this template, a truemidalways becomeshi.(lo + hi) / 2in C++ or Java. Here values are small, but get used tolo + (hi - lo) / 2. It matters in Koko Eating Bananas.
Say it in the interview
"Since the array is sorted, the question 'is nums[i] at least the target?' is false for a prefix and true for the rest. I binary search for the first index where it's true, with lo at 0 and hi at n, which stands for 'past the end'. When the true case happens I set hi to mid, and otherwise lo to mid plus one, so the answer always stays in the range. When they meet, I check that the index is in bounds and actually holds the target. That's O(log n) time and O(1) space."
Follow-ups interviewers ask
- "What if the array has duplicates and you need the first one?" This code already returns the first, because it finds the lower bound. For the last one, see Find First and Last Position of Element in Sorted Array.
- "What if the target isn't there and you must return where it would be inserted?" Return
lodirectly. It's the insertion point that keeps the array sorted. - "Can you do it recursively?" Yes, but each call adds a stack frame, so space becomes O(log n). The loop is simpler and uses O(1).
Practise the same idea
This is Day 36 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free