Binary search · Medium
Search in Rotated Sorted Array: the idea to remember.
Find a target index in a rotated sorted array of distinct integers.
The core insight
Identify which half is sorted, then check whether the target lies within that half.
Why it works
At least one half is sorted. Its endpoints tell us whether the target can occur there.
The mistake to avoid
Include the sorted half endpoint in the range check; equality at mid is handled first.
Time: O(log n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
if (nums[l] <= nums[m]) {
if (nums[l] <= target && target < nums[m]) r = m - 1;
else l = m + 1;
} else {
if (nums[m] < target && target <= nums[r]) l = m + 1;
else r = m - 1;
}
}
return -1;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.