Binary Search
Binary search finds a value or a boundary in O(log n) by halving the range that could contain the answer at every step. Everyone knows the idea; far fewer people write it correctly under pressure. Most failed binary searches in interviews are not wrong in concept but wrong at the edges: an infinite loop, a missed last element, an off-by-one in the returned index.
This lesson is for software engineering and data candidates preparing for a live coding round. It gives you one template that avoids those bugs, shows how it extends from "find a value" to "find the first position where something becomes true", and then to the most powerful form: binary search on the answer itself. Code is in Python.
When the pattern fits
The input is sorted and you need a value, its first or last occurrence, or where it would be inserted.
The constraints are large (n up to 10^5 or more, or values up to 10^9) and an O(n) scan is too slow for repeated queries, or O(n) per candidate answer is too slow.
The problem asks for a minimum or maximum value that satisfies a condition, and if a value works, every larger (or every smaller) value also works. That is binary search on the answer, and the problem rarely says "binary search" anywhere.
The array is "almost sorted": rotated, or increasing then decreasing.
The underlying requirement is always the same: a monotonic predicate. Picture the candidates laid out in order and a yes/no question about each. If the answers look like no, no, no, yes, yes, yes, binary search finds the first yes.
One template: first index where the predicate is true
Use a half-open range [lo, hi) and keep one invariant: the first true position is always somewhere in [lo, hi].
def lower_bound(nums, target):
"""First index i with nums[i] >= target; len(nums) if none."""
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] >= target:
hi = mid # mid could be the answer, keep it
else:
lo = mid + 1 # mid is not the answer, drop it
return loThree details make this template safe:
hi = len(nums), notlen(nums) - 1. "Not found" has a natural answer, the end, so you never need a special case.hi = mid, neverhi = mid - 1, whenmidmight be the answer.lo = mid + 1whenmidis ruled out. Becausemidrounds down andlo < hi,midis always less thanhi, so the range shrinks every iteration and the loop cannot run forever.
Trace on [1, 3, 3, 3, 7] with target 3: lo=0, hi=5, mid 2 holds 3, so hi=2; mid 1 holds 3, so hi=1; mid 0 holds 1, so lo=1. Return 1, the first 3.
Everything else is this template with a different predicate:
Exact search:
i = lower_bound(nums, target), then checki < len(nums) and nums[i] == target.Last occurrence: the first index with
nums[i] > target, minus one. Change>=to>.Count of a value: first index of
> targetminus first index of>= target. For the example above, 4 minus 1 is 3.Insert position:
lower_bounditself.
In languages with fixed-size integers, write mid = lo + (hi - lo) // 2 so that lo + hi cannot overflow. In Python it does not matter, but saying it shows you know.
Binary search on the answer
Many optimization problems hide a monotonic predicate. The move is: guess an answer, check whether it is feasible in O(n), and binary search over the guesses.
Prompt: "Files of the given sizes must be uploaded in order over d days. Each day you upload files in sequence until the next one would exceed the daily cap. What is the smallest daily cap that finishes within d days?"
Feasibility is monotonic: if a cap of 10 finishes in time, a cap of 11 does too. The smallest possible cap is the largest single file (it has to fit somewhere); the largest you ever need is the total (everything in one day). Search between them for the first cap that fits.
def min_daily_cap(sizes, days):
def fits(cap):
used_days, today = 1, 0
for size in sizes:
if today + size > cap:
used_days += 1
today = 0
today += size
return used_days <= days
lo, hi = max(sizes), sum(sizes)
while lo < hi:
mid = (lo + hi) // 2
if fits(mid):
hi = mid
else:
lo = mid + 1
return loTrace sizes [4, 2, 5, 3, 1] with 3 days. The range is 5 to 15.
Cap 10: days are
[4, 2],[5, 3, 1]. Two days, fits, sohi = 10.Cap 7:
[4, 2],[5],[3, 1]. Three days, fits,hi = 7.Cap 6:
[4, 2],[5],[3, 1]. Fits,hi = 6.Cap 5:
[4],[2],[5],[3, 1]. Four days, fails,lo = 6.
Answer: 6. Complexity is O(n log S), where S is the total size: log S guesses, each checked in O(n). Say both parts. The skill being scored here is problem solving: noticing that "minimize the maximum" plus a cheap feasibility check means binary search, even though nothing in the array is sorted.
Here is what separates two answers to this prompt. The weaker one tries caps upward from the largest file, one at a time, which is correct but O(n · S); when pushed, the candidate writes a binary search with lo <= hi and hi = mid, and it never terminates: once lo == hi on a cap that fits, hi = mid changes nothing. The stronger one says the linear scan first, then states the monotonic predicate in a sentence ("if a cap fits, every larger cap fits") before coding (problem solving), justifies both ends of the range (correctness), keeps fits as its own small function (code quality), tests a single file and a file larger than everything else combined (testing and edge cases), and gives the complexity in both parts (communication).
Rotated sorted arrays
Prompt: "A sorted array of distinct values was rotated at an unknown point, such as [6, 7, 9, 1, 3, 4]. Find the index of a target in O(log n)."
At any mid, at least one half is sorted. Check which, then ask whether the target lies inside that sorted half's range.
def search_rotated(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1This uses a closed range [lo, hi] with lo <= hi, because it returns as soon as it finds the value. That is fine; what matters is that you pick one convention per function and keep every line consistent with it. Trace target 3: mid 2 holds 9; the left half 6, 7, 9 is sorted but 3 is not in [6, 9), so lo = 3; mid 4 holds 3, found.
The <= in nums[lo] <= nums[mid] matters when lo == mid (a one-element left half). With duplicates allowed, this approach can no longer tell which half is sorted when nums[lo] == nums[mid]; the fix is to step lo forward by one, and the worst case becomes O(n). Mention that if asked.
Tip
Before you write the loop, say your interval convention out loud: "half-open,
lotohiexclusive, I return the first index where the predicate holds." Then check each line against it. That one sentence prevents most binary search bugs.
Testing a binary search
Binary search deserves a deliberate test pass, because its bugs hide at the boundaries. Run the code mentally on:
an empty array, and a one-element array where the target is and is not present;
a target smaller than everything and larger than everything;
a target that appears many times;
for search on the answer, the smallest and largest candidates in the range.
Doing this unprompted is what moves the testing and edge cases score.
Follow-ups to expect
The AI interviewer will ask for your interval convention or your loop's termination if you do not state them, and will ask you to test the boundaries. If you are stuck on a search-on-the-answer problem, the first hint is usually a nudge about the range of possible answers; later hints name the predicate. Each hint is counted against the dimension it helped with, weighted by how much it gave away, so say "is there a monotonic yes/no question here?" to yourself before you need one. After a working solution, expect:
"Find the first and last position of the value." Two calls to the boundary template with
>=and>."Find the peak in an array that increases then decreases." Compare
nums[mid]withnums[mid + 1]and keep the side that is still rising."Search a sorted 2D matrix." If each row continues where the previous one ended, treat it as one flattened sorted array of m · n entries and map the index back with
divmod(i, n). If rows and columns are only sorted on their own, start at the top-right corner and step left or down, O(m + n). Binary search on the value, counting entries at most the guess, is the tool for the related "kth smallest in the matrix" question."Why log n?" Each step halves the range; a range of a million needs about 20 steps.
What changes with seniority
Early-career candidates are expected to write a correct lower-bound search and test its boundaries. Mid-level candidates should recognize search on the answer from "minimize the maximum" wording without a hint and give the O(n log S) bound unprompted. Senior candidates are expected to explain why the predicate is monotonic, handle the rotated and duplicate variants, and say when binary search is the wrong tool (unsorted data queried once).
Mistakes that cost points
Mixing conventions: a half-open
hiwith a closedlo <= hiloop, orhi = mid - 1whenmidcould be the answer.Infinite loops from
lo = midwithmidrounded down.Forgetting to check the found index before reading
nums[i]; it can equallen(nums).Wrong search range on the answer, such as starting at 0 when no cap below the largest file can ever work, or ending below the true maximum.
Missing the pattern entirely on "minimize the maximum" problems and reaching for a greedy guess or dynamic programming.
Practice it
Drill for 15 minutes: write lower_bound from memory, then derive exact search, last occurrence and count from it without changing the loop. Then write min_daily_cap and trace it on [7, 2, 5, 10, 8] with 2 days (the answer is 18).
Then take Two Sum and offer the sorted-array variant as a follow-up: sort pairs of value and index, then for each value binary search for its complement, O(n log n). Previous in this series: Sliding Window. Next: Hash Maps and Prefix Sums.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Hash Maps and Prefix Sums
Use maps for lookup, counting and grouping, build prefix sums for constant-time range queries, and count or find target-sum subarrays with a map of earlier prefixes, negatives included.
8 min read
- Stacks and Monotonic Stacks
Solve nested-structure problems with a stack, find the next greater or smaller element for every position in one pass, and explain the push-once, pop-once reason it runs in linear time.
8 min read
- Heaps and Top K
Recognize when a problem needs a heap, code its four shapes (top k, k-way merge, two heaps for a running median, scheduling by earliest end) and say when a plain sort or quickselect is the better answer.
9 min read
- Trees
Decide whether information flows down a tree as arguments or up as return values, then write correct DFS, level-order BFS and BST solutions, including iterative traversal for trees too deep for recursion.
9 min read
