Understanding the Problem
We are given a rotated sorted array and a target element. Our goal is to find the index of the target using an efficient algorithm.
A rotated sorted array is one where the array was originally sorted in ascending order, but then it was rotated at some pivot. For example, [6, 7, 8, 1, 2, 3, 4]
is a rotation of [1, 2, 3, 4, 6, 7, 8]
.
The challenge here is that binary search requires a sorted array. In a rotated array, only parts of the array are sorted. So we have to modify our binary search approach to handle this.
Step-by-Step Solution with Example
step 1: Choose an example
Let’s work with the example: arr = [6, 7, 8, 1, 2, 3, 4]
and target = 2
.
step 2: Initialize search range
We set two pointers: start = 0
and end = arr.length - 1
.
step 3: Begin binary search loop
While start ≤ end
, we calculate the middle index: mid = Math.floor((start + end) / 2)
.
step 4: Check if mid is the target
If arr[mid] == target
, we return mid
— we've found the element!
step 5: Decide which half is sorted
- If
arr[start] ≤ arr[mid]
, then the left half is sorted.
- If
arr[mid] ≤ arr[end]
, then the right half is sorted.
step 6: Narrow down the search
If the left half is sorted:
- Check if
target
lies between arr[start]
and arr[mid]
.
- If yes, move
end = mid - 1
.
- If not, move
start = mid + 1
.
If the right half is sorted:
- Check if
target
lies between arr[mid]
and arr[end]
.
- If yes, move
start = mid + 1
.
- If not, move
end = mid - 1
.
step 7: Repeat until found or range is empty
Keep repeating steps 3–6 until you either find the target or the range collapses (start > end
).
step 8: Apply this to our example
Initial: start = 0
, end = 6
→ mid = 3
→ arr[mid] = 1
Right half [1, 2, 3, 4]
is sorted → and target 2
lies in that half → move start = mid + 1 = 4
New mid = (4+6)//2 = 5 → arr[5] = 3
Right half [3, 4]
is sorted → target 2
not in this half → move end = mid - 1 = 4
New mid = (4+4)//2 = 4 → arr[4] = 2
— found it!
Return index 4
Edge Cases
- Empty array: If the array is empty, return
-1
immediately.
- Single element: Compare that element with the target. If it matches, return index 0; else return
-1
.
- Target not present: Binary search will terminate with
start > end
. Return -1
.
- Already sorted array (not rotated): Binary search will still work fine using this logic.
Finally
This approach modifies binary search to handle rotated sorted arrays effectively. By determining which half is sorted at each step and checking where the target lies, we reduce the search space efficiently.
It ensures O(log n) performance and handles all edge cases clearly. Practicing with various examples and edge cases helps strengthen understanding of this clever variation of binary search.
Comments
Loading comments...