Search in Rotated Sorted Array
LeetCode 33 · Medium · solution, intuition & step-by-step walkthrough
Identify the sorted half; test whether the target lies in it.
This is how I solved Search in Rotated Sorted Array (LeetCode 33), a medium problem from the Rotated Sorted Array pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
After rotation, at least one half around mid is still sorted. Check which one, and whether the target falls inside that sorted half's range — that tells you which side to keep.
Approach
- 1
mid matches → return.
- 2
If nums[low] ≤ nums[mid], the left half is sorted: keep it if target ∈ [nums[low], nums[mid]).
- 3
Otherwise the right half is sorted: keep it if target ∈ (nums[mid], nums[high]].
- 4
Not found → −1.
How I solved it
Modified binary searchPythonO(log n) time
class Solution:
def search(self, nums: List[int], target: int) -> int:
#binary search
low=0
high =len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
return mid
if nums[low]<=nums[mid]:
#left half is sorted
if target>=nums[low] and target<nums[mid]:
high = mid-1
else:
low = mid+1
else:
#right half is sorted
if target>nums[mid] and target<=nums[high]:
low=mid+1
else:
high = mid-1
return -1Search in Rotated Sorted Array — FAQ
What is the intuition behind Search in Rotated Sorted Array?
After rotation, at least one half around mid is still sorted. Check which one, and whether the target falls inside that sorted half's range — that tells you which side to keep.
How do you solve Search in Rotated Sorted Array (LeetCode 33)?
1. mid matches → return. 2. If nums[low] ≤ nums[mid], the left half is sorted: keep it if target ∈ [nums[low], nums[mid]). 3. Otherwise the right half is sorted: keep it if target ∈ (nums[mid], nums[high]]. 4. Not found → −1.
What is the time and space complexity of Search in Rotated Sorted Array?
Time: O(log n). Space: O(1). (Accepted approach: Modified binary search.)
What are common mistakes in Search in Rotated Sorted Array?
Use ≤ in nums[low] ≤ nums[mid] for two-element ranges.