Skip to content
thesarfo

Reference

Search in a Rotated Sorted Array

Finding a target in a rotated sorted array by identifying which half is sorted at each step.

views 0

Find target in a rotated sorted array (distinct values), returning its index or -1. [4,5,6,7,0,1,2], target 04. (LeetCode 33)

Approach: at each step, one half of the array (split at mid) is guaranteed sorted. Figure out which half is sorted by comparing nums[low] and nums[mid], then check whether target falls inside that sorted half’s range — if it does, search there, otherwise search the other half.

class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) return mid;
if (nums[low] <= nums[mid]) { // left half is sorted
if (nums[low] <= target && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else { // right half is sorted
if (nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
};

Time: O(log n). Space: O(1).