Skip to content

Search in Rotated Sorted Array

There is an integer array nums sorted in ascending order. It is then rotated at some unknown pivot. Given the rotated array and a target value, return the index of target if it exists, otherwise return -1.

You must write an algorithm with O(log n) runtime complexity.

InputTargetOutputExplanation
[4, 5, 6, 7, 0, 1, 2]04Target found at index 4
[4, 5, 6, 7, 0, 1, 2]3-1Target not in array
[1]10Single element matches target
[3, 1]30Rotated array, target at start
  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values in nums are unique
  • nums is guaranteed to be rotated at some pivot
  • -10^4 <= target <= 10^4
ApproachTimeSpaceBest When
Binary SearchO(log n)O(1)Standard approach, O(log n) required
Linear SearchO(n)O(1)Very small arrays, simplicity preferred
  • Pick Binary Search to meet the O(log n) constraint and master the pattern.
  • Pick Linear Search to understand the problem conceptually first.
Required Time
Binary Search
O(log n) time · O(1) space
Simplicity
Linear Search
O(n) time · O(1) space
★ Recommended

Identify which half is sorted by comparing nums[left] with nums[mid]. Then determine if the target is in the sorted half or the unsorted half, and adjust the search accordingly.

⏱ Time O(log n) Halve search space each iteration 💾 Space O(1) Only pointers

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

StepleftrightmidSorted Halfnums[mid]In Range?Action
1063Left (4-7)7Noright = 2
2021Left (4-6)5Noright = 0
30004Noleft = 1
410Search right half, return 4
function search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
return mid
// Determine which half is sorted
if nums[left] <= nums[mid]:
// Left half is sorted
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
// Right half is sorted
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
search_in_rotated_sorted_array_binary_search.py
"""
#33 Search in Rotated Sorted Array - Binary Search Approach
Time: O(log n), Space: O(1)
A rotated sorted array has been rotated at an unknown pivot.
Use binary search to find target, identifying which half is sorted.
"""
class Solution:
def search(self, nums: list[int], target: int) -> int:
"""
Binary search on rotated array.
Determine which half is sorted, then check if target is in that half.
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
# Determine which half is sorted
if nums[left] <= nums[mid]:
# Left half is sorted
if nums[left] <= target < nums[mid]:
# Target is in sorted left half
right = mid - 1
else:
# Target is in right half
left = mid + 1
else:
# Right half is sorted
if nums[mid] < target <= nums[right]:
# Target is in sorted right half
left = mid + 1
else:
# Target is in left half
right = mid - 1
return -1
# Test cases
if __name__ == "__main__":
sol = Solution()
assert sol.search([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert sol.search([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert sol.search([1], 1) == 0
assert sol.search([1, 3], 3) == 1
assert sol.search([3, 1], 3) == 0
print("All test cases passed!")
✓ Simple

Iterate through the array and check if each element matches the target. Return the index on match or -1 if not found.

⏱ Time O(n) Full array scan 💾 Space O(1) Only pointers

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

inums[i]Match?Action
04NoContinue
15NoContinue
26NoContinue
37NoContinue
40YesReturn 4
function search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
search_in_rotated_sorted_array_linear.py
"""
#33 Search in Rotated Sorted Array - Linear Search Approach
Time: O(n), Space: O(1)
Linear scan through array to find target value.
"""
class Solution:
def search(self, nums: list[int], target: int) -> int:
"""
Simple linear search through array.
Return index if found, otherwise -1.
"""
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
# Test cases
if __name__ == "__main__":
sol = Solution()
assert sol.search([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert sol.search([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert sol.search([1], 1) == 0
assert sol.search([1, 3], 3) == 1
assert sol.search([3, 1], 3) == 0
print("All test cases passed!")
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
search_in_rotated_sorted_array_space_optimized.py
"""
Solution for Search in Rotated Sorted Array
"""
def solve():
"""Implementation for approach 3 of Search in Rotated Sorted Array"""
pass
if __name__ == "__main__":
print("Solution ready")