Search in Rotated Sorted Array - Problem

Imagine you have a sorted library bookshelf that someone accidentally rotated! ๐Ÿ“š

You're given an integer array nums that was originally sorted in ascending order with distinct values. However, before reaching you, this array was left rotated at some unknown pivot point k, where 1 โ‰ค k < nums.length.

What does rotation mean?
If we rotate [0,1,2,4,5,6,7] left by 3 positions, we get [4,5,6,7,0,1,2]. The elements [4,5,6,7] moved to the front, and [0,1,2] wrapped around to the back.

Your mission: Find the index of a target value in this rotated array, or return -1 if it doesn't exist.

The catch: You must solve this in O(log n) time complexity - no linear scanning allowed!

Examples:
โ€ข nums = [4,5,6,7,0,1,2], target = 0 โ†’ return 4
โ€ข nums = [4,5,6,7,0,1,2], target = 3 โ†’ return -1

Input & Output

example_1.py โ€” Basic rotation with target found
$ Input: nums = [4,5,6,7,0,1,2], target = 0
โ€บ Output: 4
๐Ÿ’ก Note: The target 0 is found at index 4. The array was rotated 4 positions to the left from [0,1,2,4,5,6,7].
example_2.py โ€” Target not in array
$ Input: nums = [4,5,6,7,0,1,2], target = 3
โ€บ Output: -1
๐Ÿ’ก Note: The target 3 is not present in the array, so we return -1.
example_3.py โ€” Single element array
$ Input: nums = [1], target = 0
โ€บ Output: -1
๐Ÿ’ก Note: Edge case: single element array where target is not found.

Constraints

  • 1 โ‰ค nums.length โ‰ค 5000
  • -104 โ‰ค nums[i] โ‰ค 104
  • All values of nums are unique
  • nums is an ascending array that is possibly rotated
  • -104 โ‰ค target โ‰ค 104

Visualization

Tap to expand
Book 4Book 5Book 6Book 7Book 0Book 1Book 2๐Ÿ“ MIDDLELEFT HALF: SORTED โœ“RIGHT HALF: HAS ROTATION๐ŸŽฏ Looking for Book 0Book 0 is NOT in sorted left section [4,5,6,7]โ†’ Must be in right section [0,1,2]๐Ÿ” Modified Binary Search StrategyAlways eliminate half by using the sorted property!
Understanding the Visualization
1
Look at the middle book
Find the middle position and examine that book's number
2
Identify the sorted section
Determine whether the left or right section is properly ordered
3
Check if target is in sorted section
See if your target book number falls within the ordered section's range
4
Eliminate half the shelf
Focus on the half that could contain your book and repeat
Key Takeaway
๐ŸŽฏ Key Insight: In a rotated sorted array, one half is always perfectly sorted - use this to eliminate half the search space each time, achieving O(log n) efficiency!
Asked in
Google 85 Amazon 72 Meta 65 Microsoft 58 Apple 45
71.2K Views
Very High Frequency
~15 min Avg. Time
2.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