Search in Rotated Sorted Array II — LeetCode 81 Python Solution

MediumArrayBinary Search
Problem
#81
Reading time
3 min

The problem

There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= 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 = [2,5,6,0,0,1,2], target = 0
Output
true

Python solution

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

Complexity

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

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 81. Search in Rotated Sorted Array II 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

Frequently asked questions

How hard is LeetCode 81. Search in Rotated Sorted Array II?
LeetCode 81. Search in Rotated Sorted Array II is rated Medium on LeetCode.
What is the time complexity of LeetCode 81. Search in Rotated Sorted Array II?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 81. Search in Rotated Sorted Array II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 81. Search in Rotated Sorted Array II cover?
LeetCode 81. Search in Rotated Sorted Array II 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