The βSearch in Rotated Sorted Arrayβ problem asks us to find the index of a target element in a sorted array that has been rotated at an unknown pivot. If the target exists, return its index; otherwise, return -1
.
This array is guaranteed to have been rotated but contains no duplicates. Each half of the array retains a sorted structure, which makes this an ideal case for binary search with modifications.
Example:
Input: nums = [4,5,6,7,0,1,2], target = 0
β Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
β Output: -1
This problem teaches how to adapt binary search to handle rotations β a common transformation of sorted data in problems involving circular arrays or incomplete sorting. It's frequently asked in technical interviews due to its balance of logic and binary search manipulation.
The trick to solving this efficiently is recognizing that at least one half of the array is always sorted. By determining which half is sorted at each step, we can decide where to move the search window.
left = 0
and right = nums.length - 1
.left <= right
:
mid = Math.floor((left + right) / 2)
.nums[mid] == target
, return mid
.nums[left] <= nums[mid]
: the left half is sorted.nums[left] <= target < nums[mid]
, search left: right = mid - 1
.left = mid + 1
.nums[mid] < target <= nums[right]
, search right: left = mid + 1
.right = mid - 1
.-1
.Input: nums = [4,5,6,7,0,1,2]
, target = 0
Time Complexity: O(log n), where n
is the number of elements in the array. Each iteration cuts the search space in half.
Space Complexity: O(1), as we use only constant extra memory.
The βSearch in Rotated Sorted Arrayβ problem is a brilliant example of how binary search can be extended beyond simple sorted arrays. By cleverly identifying the sorted half at each step, we can zero in on the target efficiently, even after the array has been rotated.