Binary Search — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Given a sorted array and a target value, return the index of the target. Your solution must run in O(log n) time.” You’ve seen Binary Search before. You know the concept: split the array, compare the midpoint, discard half. But now you need to write it under pressure with zero off-by-one errors, explain why your loop condition is <= and not <, and handle the follow-up about rotated arrays. That’s a very different challenge.
This walkthrough covers how that conversation unfolds: the clarifying questions worth asking, the boundary decisions that trip up even experienced engineers, and the precise verbal framing that separates confident candidates from uncertain ones.
The Problem
Given a sorted array of distinct integers nums and a target integer target, return the index of target in the array. If target is not present, return -1. Your solution must run in O(log n) time. (LeetCode #704)
Example
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
The value 9 appears at index 4 in the sorted array. The O(log n) constraint rules out a simple linear scan, and the interviewer is explicitly asking for the binary search approach. A second example: if target = 2, the output is -1 because 2 does not exist in the array.
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
Binary Search is a litmus test for precision. The algorithm has maybe five lines of meaningful logic, which means there’s nowhere to hide. Interviewers watch closely for whether you can implement a well-known algorithm cleanly, handle boundaries correctly, and explain your choices as you go.
| Skill | What Interviewers Observe |
|---|---|
| Algorithmic precision | Do you get the loop condition and pointer updates exactly right? |
| Off-by-one awareness | Do you use left <= right or left < right, and can you justify it? |
| Overflow prevention | Do you compute mid as left + (right - left) // 2 instead of (left + right) // 2? |
| Communication | Do you narrate boundary decisions or code silently and hope for the best? |
| Edge case handling | Do you test against empty arrays, single elements, and targets at the boundaries? |
| Generalization | Can you extend this to “first/last occurrence” or “search in rotated array”? |
Step 1: Clarifying Questions
Even for a well-known algorithm, asking clarifying questions before coding demonstrates discipline. Here are the most valuable ones for Binary Search:
-
Is the array guaranteed to be sorted? The problem states it is, but confirming shows you understand that binary search’s correctness depends entirely on sorted order. In a real-world variant, this might not be guaranteed.
-
Are all elements distinct, or can there be duplicates? This problem uses distinct integers, which simplifies things. With duplicates, “find the target” becomes ambiguous (first occurrence? any occurrence?). Knowing this helps you avoid over-engineering.
-
Should I return the index or the value? The problem asks for the index, a detail worth confirming, since some variants return
true/falseor the element itself. -
What should I return if the target isn’t found? The problem specifies
-1, but this is worth restating. Some interview variants ask you to return the insertion point instead (LeetCode #35). -
What are the constraints on array size? Knowing
ncan reach 10,000+ confirms that O(log n) is meaningful here. It also lets you calculate that at most ~14 iterations are needed for 10,000 elements, a satisfying fact to mention.
Step 2: A First (Non-Optimal) Idea
The obvious starting point is a linear scan: iterate through every element and return the index where the value matches the target.
def search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
| Approach | Time | Space |
|---|---|---|
| Linear scan | O(n) | O(1) |
This is correct, and for small arrays it’s perfectly reasonable. But the problem explicitly requires O(log n), and the interviewer has told you the array is sorted, which is a strong hint that you’re expected to exploit that structure.
A sorted array is a gift: it tells you that everything to the left of a given index is smaller, and everything to the right is larger. Linear search throws that information away. Binary search uses it to eliminate half the array with every comparison.
Always mention the brute force, then pivot: “Linear search works but ignores the sorted property. I can do much better by exploiting the ordering.”
Step 3: The Key Insight
A sorted array lets you make a guaranteed elimination with every comparison. Pick the middle element. If it equals the target, you’re done. If the target is less than the middle, ignore the right half. If greater, ignore the left half. Each step cuts the problem in half.
Here’s how to reason through it verbally: pick the middle element of your current search range. If it equals the target, you’re done. If the target is less than the middle element, it can only be in the left half, so you safely ignore everything to the right. If the target is greater, it can only be in the right half, so you ignore everything to the left.
Each comparison cuts the problem in half. An array of 1,000 elements needs at most 10 comparisons. An array of 1,000,000 needs at most 20. That’s the power of O(log n).
The hard part isn’t the concept. It’s the boundary conditions. Where exactly do left and right start? When does the loop end? How do you update the pointers? Getting these details right without a bug is what separates clean implementations from the “almost works” ones that fail on edge cases.
---
Step 4: Optimal Strategy
Here’s the algorithm, step by step:
- Initialize
left = 0andright = len(nums) - 1, representing the inclusive search boundaries. - While
left <= right(meaning there’s still at least one element to check): - Compute
mid = left + (right - left) // 2to find the middle index without risking integer overflow. - If
nums[mid] == target, returnmid. Found it. - If
nums[mid] < target, the target must be to the right. Setleft = mid + 1. - If
nums[mid] > target, the target must be to the left. Setright = mid - 1. - If the loop exits without finding the target, return
-1.
Two decisions deserve special attention: using left <= right (not <) ensures you check arrays with a single remaining element. And updating to mid + 1 / mid - 1 (not just mid) ensures the search space actually shrinks each iteration. Without this, you can get an infinite loop.
Python Implementation
def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1 # Inclusive boundaries
while left <= right: # Continue while search space is non-empty
# Compute mid this way to avoid integer overflow (matters in lower-level languages)
mid = left + (right - left) // 2
if nums[mid] == target:
return mid # Found the target
elif nums[mid] < target:
left = mid + 1 # Target is in the right half
else:
right = mid - 1 # Target is in the left half
return -1 # Target not in array
Style notes worth mentioning in an interview:
- The
midcomputation usingleft + (right - left) // 2instead of(left + right) // 2prevents integer overflow. In Python this doesn’t matter, but in Java or C++ it does, and mentioning it signals real-world awareness. - The
left <= rightloop condition is deliberately inclusive. It handles the case where one element remains. - Each branch updates
leftorrightpastmid, not tomid, ensuring the search space strictly shrinks every iteration.
Time & Space Complexity
| Operation | Complexity |
|---|---|
| Time | O(log n) |
| Space | O(1) |
Time: Each iteration halves the search space. Starting from n elements, after k iterations you have n / 2^k elements remaining. The loop ends when n / 2^k < 1, so k = log₂(n) iterations maximum.
Space: The iterative implementation uses only three variables (left, right, mid) regardless of input size, constant space. Note: a recursive implementation uses O(log n) space due to the call stack. This is worth mentioning as a comparison point.
Common Interview Mistakes
-
Using
left < rightinstead ofleft <= right. This causes the loop to exit one iteration early, missing the case where exactly one element remains in the search space. If that single element is your target, you’ll incorrectly return-1. -
Setting
left = midorright = midinstead ofmid ± 1. Ifnums[mid] != target, you need to excludemidfrom the next search range. Failing to do so can create an infinite loop whenleftandrightare adjacent. -
Computing
mid = (left + right) // 2. Correct in Python, but a classic integer overflow bug in Java and C++. Getting in the habit of writingleft + (right - left) // 2is worth the extra keystrokes, and mentioning it earns points. -
Not handling an empty array. If
nums = [], the loop never executes and-1is returned correctly, but only if your initialization doesn’t cause an index error. Confirm this with your interviewer or add a guard clause. -
Forgetting to test boundary targets. The most common off-by-one bugs manifest when the target is the first or last element. Mentally trace
nums = [1, 3, 5],target = 1andtarget = 5through your code before declaring it done. -
Jumping to code without explaining the loop invariant. Binary search is fundamentally about maintaining a contract: “the target, if it exists, is always within [left, right].” Candidates who explain this invariant demonstrate true understanding, not just memorization.
-
Coding silently. With a 5-line implementation, your verbal explanation is the interview. Saying nothing while you type gives the interviewer nothing to evaluate. Narrate every decision, especially the boundary choices.
What a Strong Candidate Sounds Like
“The array is sorted and I need O(log n), so binary search is the right approach. The core idea is to maintain a search window defined by
leftandrightpointers, and at each step check the midpoint. If the midpoint is my target, I return it. If it’s too small, I moveleftup pastmid. If it’s too large, I moverightdown pastmid. Either way, I eliminate half the remaining elements.The two implementation details I’m careful about: I use
left <= rightas my loop condition, notleft < right, so I don’t miss a single-element window. And I compute mid asleft + (right - left) // 2to avoid overflow. Not an issue in Python, but a good habit. If the loop exits without a match, I return -1.Let me trace through the example quickly to verify before submitting.”
Example Interview Dialogue
Interviewer: Implement binary search on a sorted array.
Candidate: Sure. Just to confirm: the array is sorted, elements are distinct, and I return the index or -1 if not found?
Interviewer: Correct.
Candidate: Great. I’ll maintain two inclusive pointers, left and right, and check the midpoint each iteration. If nums[mid] is less than the target, I move left to mid + 1. Not just mid, otherwise I risk an infinite loop. Same logic for moving right down. My loop condition is left <= right so I don’t exit too early when one element remains.
Interviewer: Why not use (left + right) // 2 for the midpoint?
Candidate: In Python it doesn’t matter, but in Java or C++, left + right can overflow a 32-bit integer if both are near INT_MAX. Writing left + (right - left) // 2 gives the same result without the overflow risk. I make it a habit.
Interviewer: What if you needed to find the first occurrence of a target in an array with duplicates?
Candidate: I’d modify the “found” branch. Instead of returning immediately when nums[mid] == target, I’d record that index as a candidate answer, then continue searching the left half by setting right = mid - 1. That way I keep narrowing until I find the leftmost match.
Related Problems to Practice
Binary search is a template, not just an algorithm. These problems all use the same divide-and-eliminate pattern in progressively less obvious ways:
- Search Insert Position (LeetCode #35). Same binary search, but return the insertion index when the target isn’t found.
- Search in Rotated Sorted Array (LeetCode #33). Binary search on a “broken” sorted array. Requires determining which half is sorted.
- Find First and Last Position of Element in Sorted Array (LeetCode #34). Two binary searches: one for the leftmost and one for the rightmost occurrence with duplicates.
- Find Minimum in Rotated Sorted Array (LeetCode #153). Uses binary search logic to find a pivot point rather than a target value.
The jump from #704 to #33 is one of the most common interview progressions. If you nail the base case, be ready to explain how you’d handle a rotated array.
Practice This in a Mock Interview
Reading a Binary Search explanation is a solid start, but this problem trips up experienced engineers because of execution under pressure, not lack of knowledge. When someone is watching, the off-by-one errors you’d catch in a quiet test environment have a way of slipping through. The loop condition that seemed obvious becomes suddenly ambiguous.
The only reliable way to build confidence with precision-dependent algorithms is to code them out, repeatedly, with feedback.
Start a mock interview for Binary Search on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap and study plans
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code