Find a Book on a Rotated Shelf

Medium · Binary Search · about 25 min

A library shelf holds books with different catalogue numbers, placed in increasing order. Then someone lifted a block of books from the left end and put it back on the right end, so the shelf is now a rotated sorted list (the block may also be empty, leaving the shelf fully sorted).

Given the shelf nums and a catalogue number target, return the index of target, or -1 if it is not on the shelf. Your search must take O(log n) steps.

Example: rotated_shelf_lookup([40, 50, 60, 10, 20, 30], 20) → 4

Example: rotated_shelf_lookup([40, 50, 60, 10, 20, 30], 35) → -1

Constraints: 0 to 100,000,000 books; all catalogue numbers are different.

Hints

  • Pick the middle book. Of the two halves around it, at least one has no break in its order. How can you tell which?
  • If the first book of the range is not bigger than the middle book, the left half is sorted. Otherwise the right half is.
  • Look in the sorted half only if the target falls between its two end values; otherwise go to the other half.

Learn the pattern first: the Binary Search lesson.

More Binary Search problems