The problem
A timetable lists departure times from earliest to latest. Several trains can leave at the same time, so a time can appear more than once. You are given the list times and a time t. Return a list [first, last]: the first index and the last index where t appears. If t is not in the list, return [-1, -1].
first_and_last([2, 4, 4, 7, 7, 7, 7, 9, 12], 7) # [3, 6]
first_and_last([1, 3, 5, 8], 5) # [2, 2]
first_and_last([1, 3, 5, 8], 4) # [-1, -1]
Your search must stay fast even when t appears half a million times.
In the large tests, the list counts every value you read from it. A binary search stays well under the limit. Anything that goes through the whole list goes over it. This includes in, .index(), list(…), sorted(…) and slicing.
Limits
- Up to about 600,000 times. At most 60 reads on the large tests.
- Return a list of two integers.
Builds on BSRC-3 First and last occurrence.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | A run in the middle | Not run | |
| 2 | A single copy | Not run | |
| 3 | Not in the list | Not run | |
| 4 | The run starts the list | Not run | |
| 5 | The run ends the list | Not run | |
| 6 | Every value the same | Not run | |
| 7 | Empty list | Not run | |
| 8 | Half a million copies, at most 60 reads | Not run | |
| 9 | Not in the list, between two long runs | Not run |