Algorithm Day67 - Search in Rotated Sorted Array
🧩 Problem Description
There is an integer array nums
sorted in ascending order (with distinct values).
Before being passed to your function, nums
is rotated at an unknown pivot index k
(0 <= k < nums.length).
Given the array nums
after the rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not.
You must write an algorithm with O(log n) runtime complexity.
💬 Examples
Example 1
1 | Input: nums = [4,5,6,7,0,1,2], target = 0 |
Example 2
1 | Input: nums = [4,5,6,7,0,1,2], target = 3 |
Example 3
1 | Input: nums = [1], target = 0 |
💡 Intuition
Since the array is rotated sorted, one half is always sorted:
- If the target lies within the sorted half, continue searching in that half.
- Otherwise, search in the other half.
This is a modified binary search.
🔢 Java Code (Binary Search)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(log n) — modified binary search.
- Space: O(1) — no extra space.
✍️ Summary
- Use binary search with conditions to detect the sorted half.
- Move search boundaries accordingly.
Related problems
lc-34
— Find First and Last Position of Elementlc-81
— Search in Rotated Sorted Array II