BSRC-P5

The rotated timetable

Practice 5 of 5Binary search11 tests

The problem

The stop numbers of a circular route were stored from smallest to largest, with no repeats. Then the list was rotated: some values from the start were moved to the end. For example, [3, 5, 9, 12, 15, 18, 22] might become [15, 18, 22, 3, 5, 9, 12]. You are not told where the rotation happened. Return the index of target, or -1 if it is not in the list.

search_rotated([15, 18, 22, 3, 5, 9, 12], 5)    # 4
search_rotated([15, 18, 22, 3, 5, 9, 12], 13)   # -1
search_rotated([1, 2, 3, 4, 5], 4)              # 3 (not rotated)

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 1,000,000 values, all different. At most 80 reads on the large tests.
  • The list may not be rotated at all, and it may be empty.

Builds on BSRC-2 The invariant and BSRC-6 Off-by-one traps.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1In the right-hand partNot run
2In the left-hand partNot run
3Not in the listNot run
4Not rotated at allNot run
5Rotated by one, target firstNot run
6Rotated so the smallest is lastNot run
7One valueNot run
8Empty listNot run
9Two valuesNot run
10A million values, at most 80 readsNot run
11A million values, target not in the listNot run