Find the bug · #28 · Numbers Medium Java
The search asks about build -647483647
A binary search for the first broken build works on small ranges and asks nonsense questions on huge ones.
On this page
The report
A tool finds the first broken build in a range by binary search, asking a service “was this build bad?”. On small ranges it works. With build numbers in the billions, it asks the service about build -647483647.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Search {
// The first bad build between 1 and lastBuild (every build after a bad one is bad too).
static int firstBad(int lastBuild, IntPredicate isBad) {
int lo = 1, hi = lastBuild;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (isBad.test(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
}Read it, then pick a line.
When lo and hi are both near two billion, what is lo + hi as an int?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
int last = 2_000_000_000;
int bad = 1_999_999_000;
IntPredicate isBad = n -> {
if (n < 1 || n > last) throw new IllegalArgumentException("asked about build " + n);
return n >= bad;
};
try {
System.out.println(Search.firstBad(last, isBad));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}It prints
asked about build -647483647
It should print
1999999000
Show the answer: the bug, the fix, and how you’d find it
The bug (line 6)
Line 6 finds the middle with (lo + hi) / 2. Once both are past about a billion, lo + hi is more than an int can hold, wraps to a negative number, and the “middle” is a negative build. lo + (hi - lo) / 2 gives the same middle without ever adding the two together.
The fix
3 static int firstBad(int lastBuild, IntPredicate isBad) {4 int lo = 1, hi = lastBuild;5 while (lo < hi) {6 int mid = (lo + hi) / 2;6 int mid = lo + (hi - lo) / 2;7 if (isBad.test(mid)) hi = mid;8 else lo = mid + 1;9 }How you’d find it
- Reproduce with a range in the billions: the second question is already about a negative build.
- A negative number from adding two positive ones is overflow. The only addition is
lo + hi: 1,000,000,001 + 2,000,000,000 is past the int limit. - Rewrite the middle so no intermediate value is bigger than
hi:lo + (hi - lo) / 2.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
check(Search.firstBad(2_000_000_000, n -> n >= 1_999_999_000) == 1_999_999_000, "a huge range");
check(Search.firstBad(10, n -> n >= 1) == 1, "the first build");
check(Search.firstBad(10, n -> n >= 10) == 10, "the last build");Where else this bites
- Every binary search over indices or values in C, C++ or Java.
- Python’s ints never overflow, so it doesn’t have this one.