Problem Statement
Given an integer array nums
sorted in ascending order, possibly rotated at an unknown pivot, and a target
, return the index of the target
if it exists, or -1 if it doesn't.
You must solve it with O(log n) runtime complexity.
Sample Test Cases
Example 1
Example 2
Example 3
Approaches
Brute Force
Idea
Iterate through the array linearly and compare each element with the target.
Steps
- Traverse the array from the first to the last element.
- Compare each element with the target.
- If found, return the index; otherwise, return -1.
Time Complexity
- O(n) where
n
is the length of the array.
Space Complexity
- O(1) since no additional space is required.
Example Code
Dry Run
For nums = [4, 5, 6, 7, 0, 1, 2]
and target = 0
:
- Compare 4, 5, 6, 7, and then find the target at index 4.
Result: 4
Efficient Approach (Binary Search)
Idea
Since the array is rotated, but both left and right halves are sorted, use binary search to find the target by checking which half is sorted and adjusting the search space accordingly.
Steps
- Initialize two pointers
low
and high
.
- Find the middle element
mid
.
- If
mid
is the target, return mid
.
- If the left half is sorted:
- Check if the target lies within this half and adjust the search range.
- If the right half is sorted:
- Check if the target lies within this half and adjust the search range.
- Repeat until the target is found or
low
exceeds high
.
Time Complexity
- O(log n) due to binary search.
Space Complexity
- O(1) as no additional space is required.
Example Code
Dry Run
For nums = [4, 5, 6, 7, 0, 1, 2]
and target = 0
:
- First
mid = 3
, value is 7. Right half is sorted, target lies in right half.
- Adjust range to
low = 4
, high = 6
.
- Second
mid = 5
, value is 1. Left half is sorted, target lies in left half.
- Adjust range to
low = 4
, high = 4
.
- Target found at index 4.
Result: 4
Example Test Case
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Efficient Approach (Binary Search)
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
- Brute Force is simple but inefficient with O(n) time complexity.
- Binary Search offers a much faster solution with O(log n) time complexity, making it the optimal approach for this problem.