Iterative C++ Binary Search
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an integer sequence nums arranged in non-decreasing order (nums[0] <= nums[1] <= ...) and an integer target, write an iterative binary search from scratch (without recursion or built-in search helpers) to locate target, handle missing values cleanly, and state the algorithm's worst-case time and auxiliary space complexity.
In a C++ interview setting, pay close attention to passing the container without copying, avoiding unsigned underflow on empty inputs, and computing midpoints without 32-bit signed overflow. For the automated judge here, implement binary_search(nums: List[int], target: int) -> int:
- Track an inclusive index window
[left, right]initialized toleft = 0andright = len(nums) - 1. - At each step, inspect
mid = left + (right - left) // 2and returnmidimmediately ifnums[mid] == target(when duplicates exist, this returns whichever matching index the midpoint probe visits first). - Return
-1whenevertargetdoes not appear innums(including whennumsis empty).
Examples
Example 1
Input: nums = [-8, -2, 4, 11, 19, 27], target = 19
Output: 4
Explanation: The first midpoint is index 2 (nums[2] = 4 < 19), narrowing the window to [3, 5]. The next midpoint is index 4 (nums[4] = 19), which matches target.
Example 2
Input: nums = [-8, -2, 4, 11, 19, 27], target = 6
Output: -1
Explanation: Probes visit index 2 (4 < 6, advancing left to 3), index 4 (19 > 6, pulling right to 3), and index 3 (11 > 6, pulling right to 2). Once left > right, 6 is confirmed absent and -1 is returned.
Example 3
Input: nums = [], target = -5
Output: -1
Explanation: Starting with left = 0 and right = -1 makes the window empty immediately, returning -1 with zero array accesses.
Example 4
Input: nums = [6, 6, 6, 6, 6, 6], target = 6
Output: 2
Explanation: With left = 0 and right = 5, the initial midpoint 0 + (5 - 0) // 2 is 2; since nums[2] == 6, index 2 is returned right away.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i], target <= 10^9numsis sorted in non-decreasing order (nums[i] <= nums[i + 1]for all0 <= i < len(nums) - 1).- Must run in
O(log n)worst-case time andO(1)auxiliary space using iteration rather than recursion.
Step-by-step walkthrough
Understand the problem and the judge contract
Note: the interview prompt asks for C++, while the automated judge here calls a Python function
binary_search(nums, target). We will build the iterative algorithm in Python so all automated tests run, and translate it line by line into production-grade C++ in a dedicated step. Whentargetappears multiple times, Example 4 (nums = [6, 6, 6, 6, 6, 6],target = 6->2) expects the index that the standard midpoint check hits first.- Input: a sorted list/array
numsin non-decreasing order (nums[0] <= nums[1] <= ..., possibly empty and possibly containing duplicates) and an integertarget. - Output: an index
iwherenums[i] == target, or-1iftargetdoes not appear innums. - Requirements: iterative loop (no recursion), safe handling of empty and not-found inputs, and clear time/space complexity analysis.
- Input: a sorted list/array
Why linear scan wastes the sorted order
Scanning
numsfrom index0ton - 1works on any unsorted array, but on a 1,000,000-element sorted array it can inspect all 1,000,000 numbers. Becausenumsis sorted, a single peek at the middle element tells us about an entire half of the array at once:nums = [ -8, -2, 4, 11, 19, 27 ], target = 19 ^ mid = 2 (value 4) 4 < 19, and everything left of mid is <= 4, so indices 0, 1, 2 are ALL ruled out in one check! Only [11, 19, 27] (indices 3..5) can possibly hold 19.Throwing away half of the remaining candidates on every check shrinks 1,000,000 elements down to 1 in at most 20 checks (
2^20 = 1,048,576).Key idea: maintain an inclusive window [left, right]
Keep two integer indices
leftandrightmarking the inclusive rangenums[left..right]of indices that could still holdtarget. We maintain a loop invariant—a simple promise that stays true at the start of every single loop iteration:Invariant: If
targetappears anywhere innums, at least one of its indices lies inside[left, right].- Start with
left = 0andright = len(nums) - 1. (Ifnumsis empty,left = 0andright = -1, so[left, right]is already empty.) - While the window is non-empty (
left <= right), check the middle indexmid = left + (right - left) // 2:- If
nums[mid] == target, returnmidimmediately. - If
nums[mid] < target, every index<= midis too small; setleft = mid + 1. - If
nums[mid] > target, every index>= midis too large; setright = mid - 1.
- If
- Once
left > right, the window is empty. By our invariant,targetcannot be anywhere innums, so return-1.
Three boundary rules prevent every classic binary-search bug: -
while left <= right(not<): whenleft == right, the window still contains 1 unchecked element (nums[left]). Using<would skip checking that element and fail on[5]withtarget = 5. -mid + 1andmid - 1(nevermid): we already checkednums[mid]and saw it was nottarget. Excludingmidguarantees the window sizeright - left + 1strictly decreases every turn, making infinite loops impossible. -left + (right - left) // 2: algebraically equal to(left + right) // 2, and prevents 32-bit integer overflow onleft + rightwhen we translate to C++.def binary_search(nums: List[int], target: int) -> int: # left, right: inclusive index bounds [left, right] of the active search window. # When nums is empty, right starts at -1 (< left == 0), so the loop skips cleanly. left = 0 right = len(nums) - 1 # Loop invariant: if target exists in nums, at least one matching index lies in [left, right]. # Use <= (not <) because a 1-element window (left == right) still has one unchecked element. while left <= right: # Write left + (right - left) // 2 so fixed-width C++ ints never overflow on left + right. mid = left + (right - left) // 2 mid_val = nums[mid] if mid_val == target: return mid # Since mid_val != target and nums is sorted, exclude mid itself (+1 / -1) so the window strictly shrinks. if mid_val < target: left = mid + 1 else: right = mid - 1 # The window [left, right] is now empty (left > right), so target is not in nums. return -1- Start with
Trace the pointers on missing, empty, and duplicate cases
Watch
L(left),M(mid), andR(right) move on Example 2 (target = 6), Example 3 ([]), and Example 4 ([6, 6, 6, 6, 6, 6]):Example 2: nums = [-8, -2, 4, 11, 19, 27], target = 6 Turn 1: [ -8, -2, 4, 11, 19, 27 ] L=0, R=5 -> M=2 (val 4 < 6) -> move L = M + 1 = 3 L M R Turn 2: [ -8, -2, 4, 11, 19, 27 ] L=3, R=5 -> M=4 (val 19 > 6) -> move R = M - 1 = 3 L M R Turn 3: [ -8, -2, 4, 11, 19, 27 ] L=3, R=3 -> M=3 (val 11 > 6) -> move R = M - 1 = 2 L R M Stop: L=3 > R=2 (empty window) -> return -1 Example 3: nums = [], target = -5 Start: L=0, R=-1 -> L <= R is False immediately -> return -1 Example 4: nums = [6, 6, 6, 6, 6, 6], target = 6 Turn 1: [ 6, 6, 6, 6, 6, 6 ] L=0, R=5 -> M = 0 + (5 - 0)//2 = 2 -> nums[2] == 6 -> return 2 L M RTranslate line by line to C++ (and avoid unsigned/overflow traps)
In C++, the algorithm is identical, with three language-specific details interviewers always check:
- Pass
const std::vector<int>& numsby const reference: passingstd::vector<int>by value copies allnintegers inO(n)time, silently ruining theO(log n)runtime before the loop even starts! - Cast
nums.size()to a signed type before subtracting1:nums.size()has unsigned typestd::size_t. On an empty vector,nums.size() - 1wraps around toSIZE_MAX(18,446,744,073,709,551,615on 64-bit platforms) instead of-1, causing an out-of-bounds crash onnums[mid]. - Avoid
left + rightoverflow: with 32-bitint(INT_MAX = 2,147,483,647), if an array has1,500,000,000elements andtargetis near the right end,left + rightexceedsINT_MAX(undefined signed overflow in C++). Writingleft + (right - left) / 2keeps every intermediate value<= right.
#include <vector> int binarySearch(const std::vector<int>& nums, int target) { int left = 0; // Cast unsigned size_t to signed int BEFORE subtracting 1 so empty vectors get right = -1. int right = static_cast<int>(nums.size()) - 1; while (left <= right) { // Safe midpoint: right - left >= 0, so this never overflows 32-bit signed int. int mid = left + (right - left) / 2; int midVal = nums[mid]; if (midVal == target) { return mid; } if (midVal < target) { left = mid + 1; } else { right = mid - 1; } } return -1; }(Note: if
numscan hold more thanINT_MAX(~2.14 billion) elements on a 64-bit machine, usestd::ptrdiff_tfrom<cstddef>forleft,right,mid, and the return type.)- Pass
Derive the time and space complexity
- Time complexity —
O(log n): Suppose the current window[left, right]holdsselements. After checkingmid, the left side has(s - 1) // 2elements and the right side hass // 2elements, so at mosts // 2elements remain. Starting fromnelements, halvingktimes leaves at mostn / 2^kelements, so the window empties in at mostfloor(log2(n)) + 1iterations, each doingO(1)arithmetic and one array read. - Space complexity —
O(1): The iterative loop uses only a handful of scalar integer variables (left,right,mid,mid_val) regardless ofn, with no recursion stack and no array copies.
- Time complexity —
Complete Python solution
from typing import Any, Dict, List, Optional, Set, Tuple def binary_search(nums: List[int], target: int) -> int: # left, right: inclusive index bounds [left, right] of the active search window. # When nums is empty, right starts at -1 (< left == 0), so the loop skips cleanly. left = 0 right = len(nums) - 1 # Loop invariant: if target exists in nums, at least one matching index lies in [left, right]. # Use <= (not <) because a 1-element window (left == right) still has one unchecked element. while left <= right: # Write left + (right - left) // 2 so fixed-width C++ ints never overflow on left + right. mid = left + (right - left) // 2 mid_val = nums[mid] if mid_val == target: return mid # Since mid_val != target and nums is sorted, exclude mid itself (+1 / -1) so the window strictly shrinks. if mid_val < target: left = mid + 1 else: right = mid - 1 # The window [left, right] is now empty (left > right), so target is not in nums. return -1✅ Submit now — all tests should pass.
Intuition & how it works
Think of playing the "higher or lower" guessing game for a secret number, or opening a thick printed dictionary right to the middle page. Because the words in a dictionary are sorted alphabetically, one glance at the middle page tells you whether your word lives in the front half or the back half—letting you ignore half of the remaining pages every single time you look.
The naive approach—scanning the array from index 0 to n - 1—ignores the sorted order completely and takes up to n comparisons (1,000,000 checks on a million-item array instead of 20). Even when candidates try to write binary search, two subtle mistakes often break it: recursive implementations waste O(log n) call-stack memory, and mismatched boundary updates (such as while left < right with an inclusive right bound, or left = mid without + 1) either miss a single-element match or get trapped in an infinite loop.
Instead, we track an inclusive index range [left, right] governed by a loop invariant (a simple rule that stays true at the start of every loop turn): if target exists in nums, at least one copy sits inside nums[left..right]. Each iteration checks mid = left + (right - left) // 2; if nums[mid] is too small we set left = mid + 1, if too big we set right = mid - 1, and if left crosses past right the window is empty and we return -1.
Walk through a tiny 6-element example with nums = [-8, -2, 4, 11, 19, 27] and target = 19:
1. Start with left = 0, right = 5. Midpoint mid = 2 has nums[2] = 4 < 19, so indices 0..2 are ruled out and left becomes 3.
2. Now left = 3, right = 5. Midpoint mid = 4 has nums[4] = 19 == 19, so we return index 4 in just 2 comparisons!
3. Had target been 6, mid = 4 (19 > 6) would set right = 3, and checking mid = 3 (11 > 6) would set right = 2, making left = 3 > right = 2 and returning -1.
Complexity
Let n be the number of elements in nums.
- Time:
O(log n)in the worst case (O(1)best case when the very first midpoint matches). Every iteration discardsmidplus at least half of the remaining window (selements shrink to at mosts // 2), so after at mostfloor(log2(n)) + 1constant-time comparisons the window is empty. - Space:
O(1)auxiliary space. The iterative loop keeps only four scalar integers (left,right,mid, andmid_val) regardless of array length, avoiding theO(log n)call stack of recursion (as long as C++ receivesconst std::vector<int>&by reference rather than copying the vector by value).
Edge cases
- Empty array (
[]):left = 0andright = -1;left <= rightis immediately false, returning-1without ever indexingnums. - Single-element array (
[5]):left = 0, right = 0enters the loop once because of<=, returning0iftarget == 5and-1otherwise. - Target at the very first (
0) or very last (n - 1) index: the window narrows all the way to[0, 0]or[n - 1, n - 1]and finds it on the final iteration. - Target smaller than
nums[0]or larger thannums[n - 1]:rightsteps down to-1(orleftsteps up ton), terminating cleanly with-1. - Duplicate elements (
[6, 6, 6, 6, 6, 6],target = 6): returns whichever matching index the midpoint probe hits first (2for length 6), not necessarily index0. - Negative integers and zero: standard
<and==comparisons work identically across negative, zero, and positive integers.
Common mistakes
- Passing
std::vector<int>by value in C++:int binarySearch(std::vector<int> nums, int target)copies allnelements before the function starts, quietly degradingO(log n)time andO(1)space toO(n)time andO(n)space! Always useconst std::vector<int>&. - Unsigned underflow on
nums.size() - 1in C++: unsigned underflow happens when subtracting from0in an unsigned integer type wraps around to the maximum possible positive number (SIZE_MAX). On an empty vector,nums.size() - 1becomes huge instead of-1; caststatic_cast<int>(nums.size()) - 1(orstd::ptrdiff_t) first. - Signed integer overflow on
(left + right) / 2in C++: signed integer overflow happens when an arithmetic sum exceeds the maximum value a fixed-width integer can store (2,147,483,647for 32-bitint), which is undefined behavior in C++. Always writeleft + (right - left) / 2(orstd::midpoint(left, right)in C++20). - Writing
while (left < right)with inclusiveright: skips checking the last remaining element whenleft == right, failing on[5]withtarget = 5. - Updating
left = midorright = midwith an inclusive window: fails to shrink a 2-element or 1-element window, causing an infinite loop. - Mixing inclusive
[left, right]and half-open[left, right)rules: a half-open interval[left, right)includesleftand excludesright(right = n,while left < right,right = mid), whereas an inclusive interval[left, right]includes both ends (right = n - 1,while left <= right,right = mid - 1). Mixing lines from the two styles is the #1 source of off-by-one bugs.
Alternative approaches
- Half-open
[left, right)loop (std::lower_boundstyle): start withleft = 0, right = nums.size()(no- 1, so unsignedstd::size_tcannot underflow on an empty vector!), loopwhile (left < right), setleft = mid + 1whennums[mid] < targetelseright = mid, and checkleft < nums.size() && nums[left] == targetafterward. Note that on duplicates like[6, 6, 6, 6, 6, 6], that variant always returns the first index (0), whereas the standard early-return loop returns2(matching Example 4). - C++ STL
std::lower_bound/ Pythonbisect_left: in production code (when not asked to implement binary search from scratch),auto it = std::lower_bound(nums.begin(), nums.end(), target);finds the first position>= targetinO(log n)time.
Follow-up questions
- How would you modify binary search to always return the first occurrence when duplicates exist? Do not return immediately when
nums[mid] == target; instead, use a half-open windowleft = 0, right = len(nums)withwhile left < right, moveleft = mid + 1whennums[mid] < target, and moveright = midwhenevernums[mid] >= target. When the loop ends atleft == right,leftis the first index withnums[left] >= target, so returnleftifleft < len(nums) and nums[left] == target, else-1. - How would you search a sorted array that has been rotated at an unknown pivot? At any midpoint
mid(for instance on[11, 19, 27, -8, -2, 4]), at least one of the two subarraysnums[left..mid]ornums[mid..right]is guaranteed to be sorted in normal order, which you can check vianums[left] <= nums[mid]. Check whethertargetfalls between the endpoints of that sorted half; if so, narrow into it, and otherwise narrow into the other half—preservingO(log n)time when elements are distinct. - How does binary search on the answer solve optimization problems without an explicit sorted array? Whenever a feasibility check
can_finish(x)satisfies a monotonic condition (meaning oncexis large enough to returnTrue, every value larger thanxalso returnsTrue, such as minimum chip bandwidth or minimum ship capacity to finish a workload on time), the virtual results[False, False, ..., True, True]are already sorted! You can binary-search the numeric range[min_x, max_x]callingcan_finish(mid)at each midpoint to find the exact minimum feasiblexinO(log(max_x - min_x))checks.
Follow-up questions
- How would you modify binary search to always return the first occurrence when duplicates exist?
- How would you search a sorted array that has been rotated at an unknown pivot?
- How does binary search on the answer solve optimization problems without an explicit sorted array?
Similar questions
- Dense and Sparse Vector Dot Product
- Multi-Tag Pub/Sub Queue and Channel Cover Design
- Ramping Up in Uncharted Systems and Resolving Senior Disagreements
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses