You are given an array 'arr' having 'n' distinct integers sorted in ascending order. The array is right rotated 'r' times
Find the minimum value of 'r'.
Right rotating an array means shifting the element at 'ith' index to (‘i+1') mod 'n' index, for all 'i' from 0 to ‘n-1'.
Input: 'n' = 5 , ‘arr’ = [3, 4, 5, 1, 2]
Output: 3
Explanation:
If we rotate the array [1 ,2, 3, 4, 5] right '3' times then we will get the 'arr'. Thus 'r' = 3.
The first line contains an integer ‘n’, representing the size of the array ‘arr’.
The second line contains ‘n’ integers, elements of ‘arr’.
Return an integer, value of ‘r’.
You don’t need to print anything, it has already been taken care of, just complete the given function.
4
2 3 4 1
3
If we right rotate the array {1, 2, 3, 4} by '3' times then we will get {2, 3, 4, 1}. Thus 'r' = 3.
3
1 2 3
0
If we right rotate the array {1, 2, 3} by '0' time then we will get {1, 2, 3}. Thus 'r' = 0.
Can you solve this in O(logn) time complexity?
1 <= ‘n’ <= 10^5
1 <= ‘arr[i]’ <= 10^9
Time Limit: 1 sec
What does the position of the minimum element tell us?
Approach:
Since we are rotating a sorted array ‘r’ times to the right, the minimum element would also be rotated ‘r’ times to the right. Thus we can perform a linear search to find the index of the minimum element and that would be our answer.
Algorithm:
O(N), where ‘N’ is the number of elements in the array ‘arr’.
We are iterating through all the elements of ‘arr’ once, time complexity is
O(N).
O(1)
We are not utilising any extra space.