Data Structures & Algorithms · Interview question

What's the bug in mid = (lo + hi) / 2?

A strong answer

Integer overflow. When lo and hi are large enough that lo + hi exceeds the maximum value of the index type, the addition overflows, wrapping to a negative or wrong value (undefined behavior for signed int), so mid lands out of bounds and the search reads invalid memory or loops wrongly. The fix is mid = lo + (hi - lo) / 2: hi - lo is non-negative and no larger than the array, so it can't overflow, and adding half of it to lo gives the same midpoint without ever forming the large sum. This isn't theoretical, it was a real bug present in widely-used binary search and mergesort implementations (famously the JDK's Arrays.binarySearch) for years. It only manifests on very large arrays, which is exactly why it survived so long undetected.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Linear & Binary Search

O(n) linear scan works on anything; O(log n) binary search needs sorted data and gives deterministic worst-case timing, plus the overflow and off-by-one bugs that haunt it.

More Linear & Binary Search questions

Browse all 472 interview questions
What's the bug in mid = (lo + hi) / 2? | EmbeddedPrep.io