Problem: Rotated Sorted Array Search
Given an array of integers A of size N and an integer B.
array A is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).
You are given a target value B to search. If found in the array, return its index, otherwise, return -1.
You may assume no duplicate exists in the array.
Array A was sorted in non-decreasing order before rotation.
Think about the case when there are duplicates. Does your current solution work? How does the time complexity change?
The first argument given is the integer array A. The second argument given is the integer B.
Return index of B in array A, otherwise return -1
1 <= N <= 1000000 1 <= A[i] <= 10^9 all elements in A are disitinct.
Input 1: A = [4, 5, 6, 7, 0, 1, 2, 3] B = 4 Output 1: 0 Explanation 1: Target 4 is found at index 0 in A.
Input 2: A = [5, 17, 100, 3] B = 6 Output 2: -1
Since before rotation, the array was sorted, this means that we can use binary search.
In a binary search algorithm, we have three indexes, low, mid and high.
The mid variable divides the array into two part, one is [low,mid] and another is [mid,high].
You can clearly see that, whatever the mid value we choose, there will be at least one part that will be sorted.
A = [4, 5, 0, 1, 2, 3] For low = 0, high = 5 mid = 0, [A[low], A[mid]] =  // Sorted mid = 1, [A[low], A[mid]] = [4, 5] // Sorted mid = 2, [A[low], A[mid]] = [4, 5, 0] // Unsorted but, [A[mid], A[high]] = [0, 1, 2, 3] // Sorted Similarly you can check for other indexes.
Once you know which part is sorted then it becomes quite easy to find which side you have to shift. See below code to understand conditions a bit further.
Time & Space Complexity
Time Complexity: O(logN)
Space Complexity: O(1)
- Ignoring space taken by input array, we have used only constant space.
Code in C++