Find the bug · #4 · Off by one Medium Java
A new high score never goes last
A leaderboard inserts each score with a binary search, and a new top score always lands second to last.
On this page
The report
The leaderboard keeps scores sorted, lowest first, and finds where each new score goes with a binary search. A new top score always lands second to last instead of at the end.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Leaderboard {
// The index where score belongs to keep the list sorted.
static int insertPosition(int[] scores, int score) {
int lo = 0, hi = scores.length - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (scores[mid] < score) lo = mid + 1;
else hi = mid;
}
return lo;
}
}Read it, then pick a line.
Can this function ever return scores.length? Should it be able to?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
int[] scores = {10, 20, 30};
System.out.println(Leaderboard.insertPosition(scores, 25));
System.out.println(Leaderboard.insertPosition(scores, 40));It prints
2 2
It should print
2 3
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 starts hi at scores.length - 1. But the answer can be scores.length: a score bigger than all the others goes after the last one. With hi one too small, that position can never come back. It should start at scores.length.
The fix
1class Leaderboard {2 // The index where score belongs to keep the list sorted.3 static int insertPosition(int[] scores, int score) {4 int lo = 0, hi = scores.length - 1;4 int lo = 0, hi = scores.length;5 while (lo < hi) {6 int mid = (lo + hi) / 2;7 if (scores[mid] < score) lo = mid + 1;How you’d find it
- Reproduce at the edges: below the smallest gives 0 (right), between two gives 2 (right), above the largest gives 2 (should be 3).
- Only the top edge fails, so look at the range the search covers.
loandhibound the answer, andhistarts at the last index, not one past it. - Ask which answers are possible: anything from 0 to
length, both included. The search range must cover all of them.
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.
int[] s = {10, 20, 30};
check(Leaderboard.insertPosition(s, 40) == 3, "after the largest");
check(Leaderboard.insertPosition(s, 5) == 0, "before the smallest");
check(Leaderboard.insertPosition(s, 20) == 1, "an equal score goes before");
check(Leaderboard.insertPosition(new int[0], 7) == 0, "empty");Where else this bites
lower_boundand Python’sbisect_leftreturn n when everything is smaller.- Any binary search: decide whether the range is inclusive or exclusive, then stay consistent.