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 to left = 0 and right = len(nums) - 1.
  • At each step, inspect mid = left + (right - left) // 2 and return mid immediately if nums[mid] == target (when duplicates exist, this returns whichever matching index the midpoint probe visits first).
  • Return -1 whenever target does not appear in nums (including when nums is 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^9
  • nums is sorted in non-decreasing order (nums[i] <= nums[i + 1] for all 0 <= i < len(nums) - 1).
  • Must run in O(log n) worst-case time and O(1) auxiliary space using iteration rather than recursion.

Step-by-step walkthrough

  1. 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. When target appears 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 nums in non-decreasing order (nums[0] <= nums[1] <= ..., possibly empty and possibly containing duplicates) and an integer target.
    • Output: an index i where nums[i] == target, or -1 if target does not appear in nums.
    • Requirements: iterative loop (no recursion), safe handling of empty and not-found inputs, and clear time/space complexity analysis.
  2. Why linear scan wastes the sorted order

    Scanning nums from index 0 to n - 1 works on any unsorted array, but on a 1,000,000-element sorted array it can inspect all 1,000,000 numbers. Because nums is 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).

  3. Key idea: maintain an inclusive window [left, right]

    Keep two integer indices left and right marking the inclusive range nums[left..right] of indices that could still hold target. We maintain a loop invariant—a simple promise that stays true at the start of every single loop iteration:

    Invariant: If target appears anywhere in nums, at least one of its indices lies inside [left, right].

    1. Start with left = 0 and right = len(nums) - 1. (If nums is empty, left = 0 and right = -1, so [left, right] is already empty.)
    2. While the window is non-empty (left <= right), check the middle index mid = left + (right - left) // 2:
      • If nums[mid] == target, return mid immediately.
      • If nums[mid] < target, every index <= mid is too small; set left = mid + 1.
      • If nums[mid] > target, every index >= mid is too large; set right = mid - 1.
    3. Once left > right, the window is empty. By our invariant, target cannot be anywhere in nums, so return -1.

    Three boundary rules prevent every classic binary-search bug: - while left <= right (not <): when left == right, the window still contains 1 unchecked element (nums[left]). Using < would skip checking that element and fail on [5] with target = 5. - mid + 1 and mid - 1 (never mid): we already checked nums[mid] and saw it was not target. Excluding mid guarantees the window size right - left + 1 strictly decreases every turn, making infinite loops impossible. - left + (right - left) // 2: algebraically equal to (left + right) // 2, and prevents 32-bit integer overflow on left + right when 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
    
  4. Trace the pointers on missing, empty, and duplicate cases

    Watch L (left), M (mid), and R (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           R
    
  5. Translate line by line to C++ (and avoid unsigned/overflow traps)

    In C++, the algorithm is identical, with three language-specific details interviewers always check:

    1. Pass const std::vector<int>& nums by const reference: passing std::vector<int> by value copies all n integers in O(n) time, silently ruining the O(log n) runtime before the loop even starts!
    2. Cast nums.size() to a signed type before subtracting 1: nums.size() has unsigned type std::size_t. On an empty vector, nums.size() - 1 wraps around to SIZE_MAX (18,446,744,073,709,551,615 on 64-bit platforms) instead of -1, causing an out-of-bounds crash on nums[mid].
    3. Avoid left + right overflow: with 32-bit int (INT_MAX = 2,147,483,647), if an array has 1,500,000,000 elements and target is near the right end, left + right exceeds INT_MAX (undefined signed overflow in C++). Writing left + (right - left) / 2 keeps 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 nums can hold more than INT_MAX (~2.14 billion) elements on a 64-bit machine, use std::ptrdiff_t from <cstddef> for left, right, mid, and the return type.)

  6. Derive the time and space complexity

    • Time complexity — O(log n): Suppose the current window [left, right] holds s elements. After checking mid, the left side has (s - 1) // 2 elements and the right side has s // 2 elements, so at most s // 2 elements remain. Starting from n elements, halving k times leaves at most n / 2^k elements, so the window empties in at most floor(log2(n)) + 1 iterations, each doing O(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 of n, with no recursion stack and no array copies.
  7. 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 discards mid plus at least half of the remaining window (s elements shrink to at most s // 2), so after at most floor(log2(n)) + 1 constant-time comparisons the window is empty.
  • Space: O(1) auxiliary space. The iterative loop keeps only four scalar integers (left, right, mid, and mid_val) regardless of array length, avoiding the O(log n) call stack of recursion (as long as C++ receives const std::vector<int>& by reference rather than copying the vector by value).

Edge cases

  • Empty array ([]): left = 0 and right = -1; left <= right is immediately false, returning -1 without ever indexing nums.
  • Single-element array ([5]): left = 0, right = 0 enters the loop once because of <=, returning 0 if target == 5 and -1 otherwise.
  • 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 than nums[n - 1]: right steps down to -1 (or left steps up to n), terminating cleanly with -1.
  • Duplicate elements ([6, 6, 6, 6, 6, 6], target = 6): returns whichever matching index the midpoint probe hits first (2 for length 6), not necessarily index 0.
  • 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 all n elements before the function starts, quietly degrading O(log n) time and O(1) space to O(n) time and O(n) space! Always use const std::vector<int>&.
  • Unsigned underflow on nums.size() - 1 in C++: unsigned underflow happens when subtracting from 0 in an unsigned integer type wraps around to the maximum possible positive number (SIZE_MAX). On an empty vector, nums.size() - 1 becomes huge instead of -1; cast static_cast<int>(nums.size()) - 1 (or std::ptrdiff_t) first.
  • Signed integer overflow on (left + right) / 2 in C++: signed integer overflow happens when an arithmetic sum exceeds the maximum value a fixed-width integer can store (2,147,483,647 for 32-bit int), which is undefined behavior in C++. Always write left + (right - left) / 2 (or std::midpoint(left, right) in C++20).
  • Writing while (left < right) with inclusive right: skips checking the last remaining element when left == right, failing on [5] with target = 5.
  • Updating left = mid or right = mid with 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) includes left and excludes right (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_bound style): start with left = 0, right = nums.size() (no - 1, so unsigned std::size_t cannot underflow on an empty vector!), loop while (left < right), set left = mid + 1 when nums[mid] < target else right = mid, and check left < nums.size() && nums[left] == target afterward. 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 returns 2 (matching Example 4).
  • C++ STL std::lower_bound / Python bisect_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 >= target in O(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 window left = 0, right = len(nums) with while left < right, move left = mid + 1 when nums[mid] < target, and move right = mid whenever nums[mid] >= target. When the loop ends at left == right, left is the first index with nums[left] >= target, so return left if left < 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 subarrays nums[left..mid] or nums[mid..right] is guaranteed to be sorted in normal order, which you can check via nums[left] <= nums[mid]. Check whether target falls between the endpoints of that sorted half; if so, narrow into it, and otherwise narrow into the other half—preserving O(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 once x is large enough to return True, every value larger than x also returns True, 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] calling can_finish(mid) at each midpoint to find the exact minimum feasible x in O(log(max_x - min_x)) checks.

Follow-up questions

Similar questions

More Cerebras interview questions

All 4 Cerebras questions →