BSRC-P2

First and last train

Practice 2 of 5Binary search9 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1A run in the middleNot run
2A single copyNot run
3Not in the listNot run
4The run starts the listNot run
5The run ends the listNot run
6Every value the sameNot run
7Empty listNot run
8Half a million copies, at most 60 readsNot run
9Not in the list, between two long runsNot run