Binary search (including on answers)
Apply binary search to sorted data and to monotonic answer spaces.
By Invicly Tech, , in Interview Preparation. About 11 minutes to read.
In short
Binary search halves a sorted range each step to find a target in O(log n). It also works on any yes/no condition that flips once, such as finding the smallest speed that is fast enough.
Explained simply
Binary search is the "guess the number" game played perfectly. Someone picks a number from 1 to 100. You guess 50. "Too high." Now you know it is between 1 and 49, so you guess 25. Every guess throws away half of what is left. Even a million options need only about 20 guesses.
It only works when the data has an order you can trust. In a sorted array, if the middle value is too small, everything to its left is too small as well. That certainty is what lets you throw half away without looking at it.
The surprise for many beginners is that binary search is not only for arrays. If you can ask a yes or no question like "can I finish in time at speed k?", and the answers go no, no, no, yes, yes, yes as k grows, you can binary search for the first yes.
The hard part is not the idea but the details: where the range starts and ends, whether to use < or <=, and whether to move to mid or mid + 1. Pick one template, understand why it works, and use it everywhere.
Press Play on a diagram to walk through it one step at a time.
- 1Set lo and hi
Range that surely contains the answer
- 2Take mid
mid = (lo + hi) // 2
- 3Test condition
Is ok(mid) true?
- 4Narrow the range
True: hi = mid. False: lo = mid + 1
- 5Return lo
Loop ends when lo == hi: first true value
- Range is array indexes
- Condition: nums[mid] >= target
- First and last position
- Rotated sorted array
- Range is possible answers
- Condition: is answer k feasible?
- Must be monotonic in k
- Koko Eating Bananas
- 1mid = 3, value 7
Left half 4..7 is sorted; 0 is not inside
- 2Search right: lo = 4
Remaining values [0, 1, 2]
- 3mid = 5, value 1
Left part 0..1 is sorted; 0 is inside
- 4Search left: hi = 4
Only index 4 remains
- 5Check index 4
Value 0: found in 3 looks
In depth
Think in invariants, not in plus or minus one
An invariant is a fact your loop keeps true on every step. For the first-true template, the fact is: the answer is always inside [lo, hi]. If ok(mid) is true, the answer could be mid itself, so hi = mid. If it is false, the answer is further right, so lo = mid + 1. The loop runs while lo < hi and stops when they meet on the answer.
Because mid = lo + (hi - lo) / 2 rounds down, mid is always less than hi, so the range shrinks every step and the loop cannot run forever. Writing it this way instead of (lo + hi) / 2 also avoids int overflow in Java.
- Answer always in [lo, hi]
- ok(mid): hi = mid
- not ok(mid): lo = mid + 1
- mid = lo + (hi - lo) / 2
First and last position of a value
To find where target starts in a sorted array, search for the first index with nums[i] >= target. That is often called lower bound. To find where it ends, search for the first index with nums[i] > target and subtract one.
The same helper answers "how many times does target appear?" (upper minus lower), "where would it be inserted?" (lower bound) and "what is the closest value?" (check lower bound and the index before it). Starting hi at nums.length lets the search answer "after the last element" when every value is smaller.
- Step 1Lower bound
First nums[i] >= 2: index 1
- Step 2Upper bound
First nums[i] > 2: index 4
- Step 3Last position
4 - 1 = index 3
- Step 4Count
4 - 1 = 3 copies
Rotated sorted arrays
A rotated array like [4, 5, 6, 7, 0, 1, 2] is two sorted pieces. At any mid, at least one half is fully sorted. Compare nums[lo] with nums[mid]: if nums[lo] <= nums[mid], the left half is sorted.
Then ask whether target lies inside that sorted half's range. If yes, search there; otherwise search the other half. Each step still discards half, so it stays O(log n). To find the minimum instead, compare nums[mid] with nums[hi]: if nums[mid] > nums[hi], the minimum is to the right of mid.
Binary search on the answer
Many "minimise the maximum" or "find the smallest capacity" problems hide a binary search. In Capacity to Ship Packages Within D Days, the answer lies between the heaviest package (anything smaller cannot carry it) and the total weight (ships everything in one day). For a guessed capacity, a greedy O(n) pass counts the days needed. If that is at most D, the capacity works, and so does anything larger.
That monotonic yes or no lets you binary search the capacity in O(n log S), where S is the total weight.
- Find the lowest and highest possible answer
- Write feasible(x) as a greedy check
- Confirm feasibility is monotonic
- Binary search for the first feasible x
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Write a bug-free binary search template~1h
- 2Find first and last positions~1h
- 3Search rotated sorted arrays~1h
- 4Binary search on the answer space~1h
- 5Practice: Koko Eating Bananas~1h
Key points
- Binary search runs in O(log n) because each step halves the range.
- Use one template (first index where the condition is true) and adapt the condition.
- On the answer: total cost is O(log range) times the cost of one feasibility check.
- For rotated arrays, one half is always sorted; check whether the target lies in it.
Key terms
Tap a card to flip it. 0/4 known
Examples
def first_true(lo, hi, ok):
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid
else:
lo = mid + 1
return lo
def min_eating_speed(piles, h): # Koko Eating Bananas
hours = lambda k: sum((p + k - 1) // k for p in piles)
return first_true(1, max(piles), lambda k: hours(k) <= h)O(n log m), where m is the largest pile.
First and last position of 8 in [5, 7, 7, 8, 8, 10]
lowerBound(8): lo = 0, hi = 6. mid 3 holds 8 >= 8, so hi = 3. mid 1 holds 7, so lo = 2. mid 2 holds 7, so lo = 3. Stop: first = 3. lowerBound(9) returns 5, the first value >= 9, so last = 5 - 1 = 4. Answer [3, 4]. If first is out of range or does not hold 8, return [-1, -1]. Two O(log n) searches.
int lowerBound(int[] a, int target) { // first i with a[i] >= target
int lo = 0, hi = a.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] >= target) hi = mid;
else lo = mid + 1;
}
return lo;
}
int[] searchRange(int[] a, int t) {
int first = lowerBound(a, t);
if (first == a.length || a[first] != t) return new int[]{-1, -1};
return new int[]{first, lowerBound(a, t + 1) - 1};
}Ship weights 1 to 10 within 5 days
lo = 10 (heaviest), hi = 55 (total). Try 32: needs 2 days, fits, hi = 32. Try 21: 3 days, hi = 21. Try 15: [1..5], [6, 7], [8], [9], [10] is 5 days, hi = 15. Try 12: 6 days, too many, lo = 13. Try 14: still 6 days, lo = 15. lo meets hi at 15, the smallest capacity that works.
int shipWithinDays(int[] w, int days) {
int lo = 0, hi = 0;
for (int x : w) { lo = Math.max(lo, x); hi += x; }
while (lo < hi) {
int cap = lo + (hi - lo) / 2, need = 1, load = 0;
for (int x : w) {
if (load + x > cap) { need++; load = 0; }
load += x;
}
if (need <= days) hi = cap; else lo = cap + 1;
}
return lo; // O(n log S) time, O(1) space
}Quick reference
- mid = lo + (hi - lo) / 2 avoids int overflow
- First true: if ok(mid) hi = mid else lo = mid + 1; loop while lo < hi
- Lower bound = first index with a[i] >= x; start hi at a.length
- Last position of x = lowerBound(x + 1) - 1
- Rotated array: one half around mid is always sorted
- On the answer: range [min possible, max possible] + monotonic feasible(x)
- Cost: O(log of range × cost of one check)
Common mistakes
- Using while lo <= hi with hi = mid, which loops forever.
- Mixing templates and getting off-by-one results.
- Applying it to a condition that is not monotonic.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Search Insert Position: return the index of target in a sorted array, or the index where it would be inserted.
- Exercise 2medium
Find Minimum in Rotated Sorted Array (no duplicates) in O(log n).
- Exercise 3hard
Split Array Largest Sum: split nums into k non-empty contiguous parts so that the largest part sum is as small as possible.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use lo <= hi or lo < hi?
- Either works if you stay consistent. lo <= hi suits exact-match searches that return mid; lo < hi with hi = mid suits "first index where something is true". Mixing parts of both templates causes infinite loops.
- Can I just use Arrays.binarySearch?
- For a plain lookup, yes, and mentioning it is good. But with duplicates it may return any matching index, not the first, and interviewers usually want you to write the search yourself.
- How do I spot binary search on the answer?
- Look for "minimum possible maximum", "smallest speed, capacity or days such that", or a huge answer range with a check you can run in O(n). If a bigger answer always stays valid, you can binary search it.