Algo-Sim › Binary Search
Search in Rotated Sorted Array
Medium · Binary Search · step through it in Java, Python and C++ on your own input
Find target in a sorted array of distinct values that was rotated at an unknown pivot, in O(log n).
Problem
An array of distinct integers was sorted in increasing order and then rotated: some prefix was moved to the end, as in [4, 5, 6, 7, 0, 1, 2]. Given this array and a target, return the index of target, or -1 if it is absent, in O(log n) time.
Constraints
- 1 ≤ nums.length ≤ 5000
- -10⁴ ≤ nums[i], target ≤ 10⁴
- All values are distinct
- Must run in O(log n)
Edge cases to test
- Not rotated
- Target at the pivot
- Target missing
Follow-up questions
- What if values can repeat?
- When
nums[lo] == nums[mid] == nums[hi], shrink both ends by one; the worst case becomes O(n) (LC 81). - Is there a two-phase approach?
- Find the rotation point (the minimum) first, then binary search the correct half: two O(log n) searches.
Solution
Java
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[lo] <= nums[mid]) {
if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
} else {
if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}Python
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target: return mid
if nums[lo] <= nums[mid]:
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int search(vector<int> &nums, int target) {
int lo = 0, hi = int(nums.size()) - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target)
return mid;
if (nums[lo] <= nums[mid]) {
if (nums[lo] <= target && target < nums[mid])
hi = mid - 1;
else
lo = mid + 1;
} else {
if (nums[mid] < target && target <= nums[hi])
lo = mid + 1;
else
hi = mid - 1;
}
}
return -1;
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)