Search in Rotated Sorted Array — LeetCode 33 Python Solution

MediumArrayBinary Search
Problem
#33
Reading time
3 min

The problem

There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).

Example

Input
nums = [4,5,6,7,0,1,2], target = 0
Output
4

Python solution

Python
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        n = len(nums)
        left, right = 0, n - 1
        while left < right:
            mid = (left + right) >> 1
            if nums[0] <= nums[mid]:
                if nums[0] <= target <= nums[mid]:
                    right = mid
                else:
                    left = mid + 1
            else:
                if nums[mid] < target <= nums[n - 1]:
                    left = mid + 1
                else:
                    right = mid
        return left if nums[left] == target else -1

Complexity

MeasureComplexity
TimeO(\log n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 33. Search in Rotated Sorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 33. Search in Rotated Sorted Array?
LeetCode 33. Search in Rotated Sorted Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 33. Search in Rotated Sorted Array?
The Python solution on this page runs in O(\log n), where n is the length of the array nums.
What is the space complexity of LeetCode 33. Search in Rotated Sorted Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 33. Search in Rotated Sorted Array cover?
LeetCode 33. Search in Rotated Sorted Array is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview