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