iq.lab
Python starts when a code cell comes near or you run one
mediumBinary search target 25 min

Search a rotated sorted list

Start with different integers in order from smallest to largest. Cut the list into two pieces and swap the pieces: that is a rotated list. For example, [1, 2, 4, 6, 7, 9] cut before the 6 becomes [6, 7, 9, 1, 2, 4]. The cut may also be at the very start, which leaves the list in order.

You get the rotated list nums and a number target. Find target and return its index; when it does not appear, return -1. Each call must take O(log n) time, where n is the length of the list and log n is how many times n can be halved before it reaches 1. A scan of the whole list is too slow.

Example 1
Inputnums = [6, 7, 9, 1, 2, 4], target = 2Output4

2 is in the second piece, at index 4.

Example 2
Inputnums = [6, 7, 9, 1, 2, 4], target = 8Output-1

8 is not in the list.

Example 3
Inputnums = [1, 3, 5], target = 5Output2

A cut at the start leaves the list sorted, and 5 is at index 2.

Constraints
  • 1 ≤ len(nums) ≤ 105

  • -109 ≤ nums[i], target ≤ 109

  • All numbers in nums are different.

  • nums is a sorted list rotated at some position, possibly 0.

  • Each call: O(log n) time.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.