IntermediateMath for DSABinary Search

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

  1. lo + hi = 4,100,000,000 > 2,147,483,647 → overflows to a negative number → index error.
  2. 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.

lo, hi ← 1, n
while lo < hi:
mid ← lo + (hi − lo) // 2(never adds two huge numbers)
if is_bad(mid): hi ← mid
else: lo ← mid + 1
return lo

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

1
2
3
4
5
6
7
8
lo = 1hi = 8

Solution · Pythonline 2

def first_bad_version(n, is_bad):
lo, hi = 1, n
while lo < hi:
mid = lo + (hi - lo) // 2 # same as (lo + hi) // 2, overflow-safe
if is_bad(mid):
hi = mid
else:
lo = mid + 1
return lo

Step 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

Where it comes up

Go further