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 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
2560012Unsorted transitionSorted portionTarget: 0 (Found!)
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!
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 22 Apple 18
52.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen