When interviewers ask you to "find the smallest X that satisfies Y" or to "search in a sorted array", they are often hinting at binary search. The pattern is simple: you repeatedly cut the search space in half until you isolate the answer. The trick is recognizing when the underlying property is monotonic – that is, once a condition becomes true it stays true (or once it becomes false it stays false).
1. Core idea of binary search
Binary search maintains two pointers, lo and hi, that bound the range of possible answers. At each step you compute mid = lo + (hi - lo) // 2 and evaluate a predicate check(mid). If check(mid) is true, you know the answer lies at mid or to the left, so you move hi = mid. Otherwise the answer is to the right, so you set lo = mid + 1. The loop ends when lo == hi, and that value is the smallest index (or value) that satisfies the predicate.
Why it works
The predicate must be monotonic: false … false … true … true. With this property, the interval always shrinks toward the boundary between false and true. Because each iteration halves the interval, the algorithm runs in O(log N) time and O(1) extra space.
2. Signals that binary search is appropriate
| Signal | Typical phrasing in a problem |
|---|---|
| Sorted data | "array is sorted", "list of timestamps in increasing order" |
| Decision boundary | "minimum capacity that allows X", "earliest day you can finish" |
| Searchable range | "values lie between A and B", "answer is an integer between 0 and 10⁹" |
| Feasibility test | "can we schedule all jobs with K machines?" |
If you see any of these, pause and ask yourself: Can I turn the question into a yes/no test? If the answer is yes, binary search is likely the right tool.
3. Worked example in Python
Problem: You have a sorted list of distinct integers nums. Return the index of the first element that is greater than or equal to a target t. If all elements are smaller, return len(nums).
def lower_bound(nums, t):
lo, hi = 0, len(nums) # hi is exclusive
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] >= t:
hi = mid # candidate found, keep it leftward
else:
lo = mid + 1 # move right
return lo
Explanation:
lostarts at the first possible index,hiat one past the last (makes the loop condition clean).- The predicate
nums[mid] >= tis monotonic: once true, it stays true for larger indices. - When the loop exits,
loequals the smallest index where the predicate holds, orlen(nums)if it never holds.
Complexity: The loop runs at most ⌈log₂(n+1)⌉ times, each iteration does O(1) work, so total time is O(log n) and space is O(1).
4. Common pitfalls and how to avoid them
- Off‑by‑one errors – mixing inclusive and exclusive bounds leads to infinite loops. Keep
hiexclusive (or inclusive) consistently and adjust the update rules accordingly. - Overflow in
mid– in languages with fixed‑size integers,lo + hican overflow. Uselo + (hi - lo) // 2(as shown) or language‑provided safe midpoint functions. - Non‑monotonic predicate – if the condition can flip back and forth, binary search will give the wrong answer. Verify monotonicity with a few mental examples.
- Wrong return value – remember whether you need the index, the value, or a sentinel like
-1orlen(nums). Adjust the final return accordingly. - Missing edge cases – test with empty arrays, single‑element arrays, and targets outside the range.
5. Five practice problems (descriptions, not full statements)
5.1. Minimum Eating Speed
You have n piles of bananas. You can eat at most k bananas per hour. Find the smallest integer k that lets you finish all piles within H hours.
Hint: The predicate “can finish in H hours with speed k” is monotonic decreasing as k grows.
5.2. Find Peak Element in a Mountain Array
Given a mountain array (strictly increasing then strictly decreasing), return the peak index.
Hint: Compare mid with its right neighbor; if mid is lower, the peak lies to the right.
5.3. Allocate Minimum Number of Pages
You have m books with page counts pages[i]. Distribute them to k students in order, minimizing the maximum pages any student reads.
Hint: Predicate “can allocate with maxPages = X” is monotonic; binary search on X.
5.4. Smallest Subarray with Sum ≥ S
Given a sorted list of positive integers, find the length of the smallest contiguous subarray whose sum is at least S. Return -1 if none exists.
Hint: Use prefix sums and binary search for each start index, or binary search on length.
5.5. Kth Smallest Distance Pair
Given an array nums, find the k‑th smallest absolute difference between any two elements.
Hint: The predicate “there are at least k pairs with distance ≤ d” is monotonic in d. Binary search on d.
These problems cover classic “minimum feasible value”, “search in a transformed space”, and “boundary detection” scenarios. Working through them builds the intuition needed to spot binary search quickly.
6. Using Call Assistant to sharpen your delivery
When you rehearse an answer, you can run the solution aloud while Call Assistant listens and suggests concise phrasing. It also helps you stay on topic for follow‑up questions, ensuring your story stays grounded in the specifics of your resume.
7. How to practice this
- Identify the predicate – for each practice problem, write a one‑line
check(x)that returns a boolean. - Implement the loop – code the binary search skeleton first, then plug in your predicate.
- Run edge‑case tests – create at least three tests: empty input, smallest possible answer, and largest possible answer.
FAQ
Q: When should I prefer linear scan over binary search? A: If the input size is tiny (under a few hundred elements) or the predicate is expensive, a linear scan may be simpler and faster in practice.
Q: Can binary search be used on unsorted data? A: Only if you can transform the problem into a monotonic decision space that does not rely on ordering, such as searching over a range of possible values.
Q: How do I handle floating‑point answers? A: Use a tolerance (
epsilon) and loop untilhi - lo < epsilon. The predicate should compare with the tolerance accordingly.Q: What’s a good way to explain my binary‑search solution to an interviewer? A: Start with the decision predicate, describe the invariant (
lois always false,hialways true), walk through one iteration, and finish with the complexity analysis.
Frequently asked questions
When should I prefer linear scan over binary search?
If the input size is tiny (under a few hundred elements) or the predicate is expensive, a linear scan may be simpler and faster in practice.
Can binary search be used on unsorted data?
Only if you can transform the problem into a monotonic decision space that does not rely on ordering, such as searching over a range of possible values.
How do I handle floating-point answers?
Use a tolerance (epsilon) and loop until hi - lo < epsilon. The predicate should compare with the tolerance accordingly.
What’s a good way to explain my binary-search solution to an interviewer?
Start with the decision predicate, describe the invariant (lo is always false, hi always true), walk through one iteration, and finish with the complexity analysis.
#coding pattern#binary search#interview prep#algorithm#python