Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Binary search on large indices in C++ (int is 32-bit).

Problem: Binary search on large indices in C++ (int is 32-bit).
int lo = 2000000000, hi = 2100000000;
int bad  = (lo + hi) / 2;          // signed overflow
int good = lo + (hi - lo) / 2;
cout << bad << " " << good;        // typical result on 2's-complement hardware
What is printed?
  1. A. -97483648 2050000000
  2. B. 2050000000 2050000000
  3. C. -2050000000 2050000000
  4. D. 97483648 2050000000

Correct answer: A. -97483648 2050000000

lo + hi = 4.1 × 10⁹ exceeds INT_MAX (≈ 2.147 × 10⁹). Signed overflow is undefined behaviour in C++; on typical hardware it wraps to −194967296, and halving gives −97483648 – a negative 'midpoint'. lo + (hi − lo)/2 never exceeds hi. This is why the safe formula is standard in binary search on the answer.

More Coding Interview Problems questions

Exams that ask this topic