![]() |
VOOZH | about |
Given a sorted and rotated array (possibly with duplicates), determine if a given key exists in it, returning true if found, otherwise false.
Examples:
Input: arr[] = [3, 3, 3, 1, 2, 3], key = 3
Output: true
Explanation: 3 is present in the array.Input: arr[] = [3, 3, 3, 1, 2, 3], key = 11
Output: false
Explanation: 11 is not present in the given array.
Table of Content
A simple approach is to iterate through the array and check for each element, if it matches the target then return the index, otherwise return -1. To know more about the implementation, please refer Introduction to Linear Search Algorithm.
This approach applies a modified version of binary search directly to the entire rotated array. At every iteration, the middle element is checked against the key. If itβs not the key, we determine whether the left half or right half is sorted by comparing values at arr[lo] and arr[mid]. If the left half is sorted and the key lies within its range, we adjust hi = mid - 1; otherwise, we shift lo = mid + 1. If the right half is sorted and the key lies within its range, we move lo = mid + 1; else, hi = mid - 1.
true
Time Complexity: O(n), Its time complexity is O(log n) for most cases but can degrade to O(n) in the worst case when the array contains many duplicates.
Auxiliary Space: O(1)