Skip to contentKEEP THE CRAFTTHE SANCTUARY

Search a Rotated Sorted Array

Find a target in a sorted array that was rotated, still in O(log n) time.

The problem

Implement Solution.search(nums, target). nums holds distinct integers that were sorted in increasing order and then rotated by some number of positions, possibly zero; for example [0, 1, 2, 4, 5, 6, 7] might become [4, 5, 6, 7, 0, 1, 2]. Return the index of target, or -1 if it is not in nums. Your solution must run in O(log n) time. nums has 1 to 5,000 values, and every value and target are between -10,000 and 10,000.

Starter code

class Solution:
    def search(self, nums: list[int], target: int) -> int:
        pass

Public examples

  1. nums = [4, 5, 6, 7, 0, 1, 2], target = 0gives4
  2. nums = [4], target = 4gives0
  3. nums = [1, 3, 5, 7], target = 1gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.