The safe midpoint: lo + (hi − lo) // 2
(lo + hi) / 2 can in Java and C++ when both are large. lo + (hi − lo) / 2 gives the same middle and never overflows.
The idea
In languages with 32-bit ints, lo + hi can exceed 2³¹ − 1 even when both fit, and the sum wraps to a negative number. hi − lo is never larger than the range itself, so lo + (hi − lo) / 2 is always safe.
Python ints don't overflow, but the habit matters in interviews, and the formula also makes the rounding explicit: it rounds toward lo.
Worked example
lo = 2,000,000,000 and hi = 2,100,000,000 in Java
- lo + hi = 4,100,000,000 > 2,147,483,647 → overflows to a negative number → index error.
- hi − lo = 100,000,000 → / 2 = 50,000,000 → lo + that = 2,050,000,000. Correct.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
n = 8, versions 5… are bad
Solution · Pythonline 2
def first_bad_version(n, is_bad):lo, hi = 1, nwhile lo < hi:mid = lo + (hi - lo) // 2 # same as (lo + hi) // 2, overflow-safeif is_bad(mid):hi = midelse:lo = mid + 1return loStep 1 of 5· line 2
Binary search for the first bad version. The midpoint is written lo + (hi − lo) // 2: the same value as (lo + hi) // 2, but it never adds two huge numbers, so it can't overflow in Java or C++.
- inside the window
, unchanged.
How to spot it
- Any on large ranges: indices up to 2³¹, or searching over answer values like 1..10⁹.
Common mistakes
- Fixing overflow with (lo + hi) >>> 1 in Java and then porting it to C++, where >>> doesn't exist.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →