Problem of the day
You are given a rotated sorted array 'a' of length 'n' and a 'key'. You need to determine if the 'key' exists in the array 'a'.
The given sorted array is rotated from an unknown index 'x'. Such that after rotation the array became [a[x], a[x+1]...., a[n-1], a[1]..., a[x-1]], (0-based indexing). For example, if the array is [1, 2, 3, 4, 5] and x = 2 then the rotated array will be [3, 4, 5, 1, 2, 3].
Return True if the 'key' is found in 'a'. Otherwise, return False.
Note: Array ‘a’ may contain duplicate elements.
Example:
Input: a = [6, 10, 1, 3, 5], key = 3
Output: True
Explanation: The array 'a' contains the 'key' = 3, so we return True.
The first line of the input contains two integers, 'n' and 'key', separated by a space.
The next line contains 'n' space-separated integers representing the elements of the array 'n'.
Return a boolean 'true' or 'false' as stated in the problem statement. 'True' is printed for a returned value of 'true' and 'False' otherwise.
You don’t need to print anything. Just implement the given function.
7 4
3 4 5 0 0 1 2
True
Input: a = [3, 4, 5, 0, 0, 1, 2], key = 4
Output: True
Explanation: The array 'a' contains the 'key' = 3, so we return True.
6 47
31 44 56 0 10 13
False
Try to solve this with average time complexity O(log(n)).
1 <= 'n' <= 10^5
0 <= 'a[i]', 'key' <= 10^9
Time Limit: 1 sec
We can linearly iterate over the array to find the ‘key’.
Approach:
Algorithm:
Function bool searchInARotatedSortedArrayII( int []‘A’, int ‘key’)
O( N ), Where ‘N’ is the array ‘A’ length.
Iterating over an array of length ‘N’ takes O(N) complexity. Hence, the overall time complexity will be O( N ).
O( 1 ).
We are taking O( 1 ) extra space for variables. Hence, the overall space complexity will be O( 1 ).