A code review from someone who's 'always written it this way': mid = (lo + hi) / 2. Worked for twenty years! Then the inputs grew toward INT_MAX, the sum overflowed, and the search wandered into negative indices. UB doesn't age — it waits. Rewrite the midpoint so it cannot overflow, staying in plain int.
The textbook midpoint (a + b) / 2 is a famous bug: for large operands a + b overflows, and signed integer overflow is undefined behaviour. Fix midpoint so it is correct for every pair of ints.
int inputs — no signed overflow (UBSan must stay clean)long long / int64 — solve it in int arithmetica + (b - a) / 2 avoid the overflow that (a + b) / 2 hits?a + (b - a) / 2 computes the same midpoint but only ever adds a half-distance to a, so it cannot overflow.
Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.