Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Search in Rotated Sorted Array in Python
Consider we have an array sorted in ascending order that is rotated at some unknown pivot. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. Given a target value to search, we return its index if found, otherwise return -1. We assume no duplicates exist in the array.
Algorithm
We use a modified binary search approach ?
- Initialize
low = 0andhigh = length of array - While
low < high:- Calculate
mid = low + (high - low) // 2 - If
arr[mid] == target, returnmid - If
arr[low] <= arr[mid](left half is sorted):- If
target >= arr[low]andtarget < arr[mid], search left:high = mid - Otherwise, search right:
low = mid + 1
- If
- Otherwise (right half is sorted):
- If
target <= arr[high-1]andtarget > arr[mid], search right:low = mid + 1 - Otherwise, search left:
high = mid
- If
- Calculate
- Return
-1if not found
Example
Let's implement this solution ?
class Solution:
def search(self, nums, target):
low = 0
high = len(nums)
while low < high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]:
if target >= nums[low] and target < nums[mid]:
high = mid
else:
low = mid + 1
else:
if target <= nums[high-1] and target > nums[mid]:
low = mid + 1
else:
high = mid
return -1
# Test the solution
solution = Solution()
result = solution.search([4, 5, 6, 7, 0, 1, 2], 0)
print(f"Index of target 0: {result}")
# Test with another example
result2 = solution.search([4, 5, 6, 7, 0, 1, 2], 3)
print(f"Index of target 3: {result2}")
Index of target 0: 5 Index of target 3: -1
How It Works
The key insight is that in a rotated sorted array, at least one half is always sorted. We determine which half is sorted and check if our target lies in that sorted range. If yes, we search that half; otherwise, we search the other half.
Time and Space Complexity
The time complexity is O(log n) as we eliminate half of the search space in each iteration. The space complexity is O(1) as we only use a constant amount of extra space.
Conclusion
Searching in a rotated sorted array uses modified binary search by identifying which half is sorted and determining if the target lies in that range. This maintains O(log n) time complexity even with rotation.
