11/41
Part 2 of 7 · Binary searchLearn
The answer can be 0 or len(times), so hi starts at len(times)
Both edges come out right, with no special case.
print(first_at_or_after(times, 50))
print(first_at_or_after(times, 700))
0
8
The answer is a place between items, not an item. Eight times have nine such places:
| Target | Answer | The place |
|---|---|---|
| 50 | 0 | before every time |
| 250 | 4 | between 220 and 300 |
| 700 | 8 | after every time: len(times) |
Target 50 returns 0: nothing is below it. Target 700 returns 8, which is len(times): everything is below it, and there's no next change. Neither edge needs a special case.
That's why hi starts at len(times) and not at the last index. Start it at len(times) - 1 and the loop can never return 8.