Search a Rotated Sorted Array in One Binary-Search Pass
eBaySoftware Engineer · Technical ScreenLast updated
Implement a single-pass binary search to locate a target value in a rotated strictly increasing array in logarithmic time and constant auxiliary space.
Problem Statement
You are given an integer array nums sorted in strictly ascending order with distinct values. Prior to being passed to your function, nums was possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
Given the rotated array nums and an integer target, return the index of target if it exists in nums, or -1 if it is not present.
You must design an algorithm with O(log n) runtime complexity that operates in a single binary-search pass (without finding the pivot index first) and does not modify the input array.
Function Signature
def search_rotated_array(nums: list[int], target: int) -> int:
pass
Input & Output Format
- Input: A list of integers
numsand an integertarget. - Output: An integer representing the 0-based index of
targetinnums, or-1iftargetis not found.
Examples
Example 1
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output: 4
Explanation: 0 is located at index 4.
Example 2
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output: -1
Explanation: 3 is not present in nums.
Example 3
Input: nums = [1], target = 0
Output: -1
Explanation: nums contains only 1 element, which does not match target.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- All values in
numsare unique. numsis guaranteed to be rotated at some index, or not rotated at all.-10^9 <= target <= 10^9
Edge Cases to Consider
- Array with only one or two elements.
- Array that was not rotated (or rotated by
nsteps, returning to original order). - Target located at the extreme ends (
nums[0]ornums[-1]). - Target located immediately before or after the rotation point.
Hints
Hint 1
In any rotated sorted array, splitting the array at index mid will always leave at least one of the two halves strictly sorted.
Hint 2
Compare nums[mid] with nums[left] to determine whether the left half or the right half is sorted.
Hint 3
Once the sorted half is identified, check if target falls within that half's boundary values; if so, discard the other half, otherwise discard the sorted half.
Follow-up questions
- How does the algorithm change if the array contains duplicate elements, and what does the worst-case time complexity become?
- How would you adapt this single-pass invariant logic to find the minimum element in the rotated array instead of a target?
- If millions of read queries are performed on the same static rotated array, what precomputations or optimizations would you consider?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.