Fix the off-by-one
Standard · Find the bug · about 6 min
This binary search should return the index of target, or -1 when it is missing. It fails on some inputs where the target is present. Click the line with the bug, then fix it.
Example 1
Input:
[[7],7]
Output:
0
The buggy code returns -1 here.
Example 2
Input:
[[1,3,4,7],7]
Output:
3
The buggy code also returns -1 here.
Constraints
- 0 ≤ nums.length ≤ 10,000
- nums is sorted ascending with distinct values
Learn the idea first: Binary search, a visual lesson.
More Binary search problems
- Mid values Warm-up
- Find the target Standard
- Implement binary search Standard
- Square root floor Standard
- Search insert position Challenge