Search in Rotated Sorted Array II - Problem
Search in Rotated Sorted Array II
Imagine you have a sorted array that's been rotated at some unknown point. Think of it like a circular bookshelf that someone spun - the books are still in order, but the starting point has changed!
You're given an integer array
Example: The array
Your Mission: Given this rotated array and a
Imagine you have a sorted array that's been rotated at some unknown point. Think of it like a circular bookshelf that someone spun - the books are still in order, but the starting point has changed!
You're given an integer array
nums that was originally sorted in non-decreasing order (with possible duplicates). Before reaching your function, this array was rotated at an unknown pivot index k, transforming [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]].Example: The array
[0,1,2,4,4,4,5,6,6,7] rotated at index 5 becomes [4,5,6,6,7,0,1,2,4,4].Your Mission: Given this rotated array and a
target value, return true if the target exists in the array, false otherwise. The challenge is to do this efficiently - can you beat the obvious linear search? Input & Output
example_1.py โ Basic rotation with target present
$
Input:
nums = [2,5,6,0,0,1,2], target = 0
โบ
Output:
true
๐ก Note:
The array was originally [0,0,1,2,2,5,6] and rotated. The target 0 exists at indices 3 and 4, so we return true.
example_2.py โ Target not present
$
Input:
nums = [2,5,6,0,0,1,2], target = 3
โบ
Output:
false
๐ก Note:
The target 3 does not exist anywhere in the rotated array, so we return false.
example_3.py โ All duplicates edge case
$
Input:
nums = [1,0,1,1,1], target = 0
โบ
Output:
true
๐ก Note:
Even with many duplicates making it hard to determine rotation point, the target 0 exists at index 1.
Constraints
- 1 โค nums.length โค 5000
- -104 โค nums[i] โค 104
- -104 โค target โค 104
- nums is guaranteed to be rotated at some pivot
- Follow up: This problem is similar to Search in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?
Visualization
Tap to expand
Understanding the Visualization
1
Find the Middle
Look at the middle element to divide the search space
2
Identify Sorted Half
Compare endpoints to determine which half maintains sorted order
3
Check Target Range
See if target could be in the sorted half
4
Eliminate & Repeat
Discard the half that can't contain target and repeat
Key Takeaway
๐ฏ Key Insight: In a rotated sorted array, we can always identify at least one sorted half and use that information to eliminate half the search space efficiently!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code