![]() |
VOOZH | about |
Given a sorted array arr[] (in strictly increasing order) that has been right-rotated k times. A right rotation means the last element is moved to the first position, and the remaining elements are shifted one position to the right. Find the value of k the number of times the array was right-rotated from its originally sorted form.
Examples:
Input: arr[] = [15, 18, 2, 3, 6, 12]
Output: 2
Explanation:
Original sorted array = [2, 3, 6, 12, 15, 18]
After 2 right rotations → [15, 18, 2, 3, 6, 12]Input: arr[] = [7, 9, 11, 12, 5]
Output: 4
Explanation:
Original sorted array = [5, 7, 9, 11, 12]
After 4 right rotations → [7, 9, 11, 12, 5]Input: arr[] = [7, 9, 11, 12, 15]
Output: 0
Explanation: Array is already sorted, so k = 0
Table of Content
The idea is that in a right-rotated sorted array, the smallest element marks the point of rotation.
By scanning through the array to find this smallest element, its index directly gives the number of rotations performed.
2
The idea is to use binary search to quickly locate the smallest element, which reveals the rotation count.
In a rotated sorted array, the smallest element is the only one smaller than both its neighbors.
At each step, we check if the current range is already sorted if it is, the first element is the smallest, and its index is the answer.
Otherwise, we decide which half to explore by comparing the middle element with the last element:
if arr[mid] is greater than arr[high], the smallest lies to the right; otherwise, it lies to the left.
2