Binary Search Lower and upper bounds
231. How Many Times Is a Sorted Array Rotated
You are given an array nums of distinct integers. It was made by sorting some integers in increasing order
and then rotating the sorted array some number of times, between 0 and nums.length − 1. Return the number
of rotations.
Rotating an array once moves its last element to the front. For example, rotating [1, 3, 5, 7, 9] once
gives [9, 1, 3, 5, 7], and rotating it twice gives [7, 9, 1, 3, 5].
Aim for O(log n) time.
Example 1
Input: nums = [27, 35, 48, -14, -6, 0, 9, 21]
3Explanation: The sorted array [-14, -6, 0, 9, 21, 27, 35, 48] was rotated three times. Each rotation moved one of
48, 35 and 27 to the front, so the smallest value, −14, now sits at index 3.
Example 2
Input: nums = [-5, 2, 8, 19, 40]
0Explanation: The array is still sorted, so it was rotated zero times.
Example 3
Input: nums = [-3, 7, 1000000000, -1000000000]
3Explanation: The sorted array [-1000000000, -3, 7, 1000000000] was rotated three times, the most a 4-element array
allows. Every value except the smallest moved to the front, so the smallest is now last.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109- All values in
numsare distinct. numsis an array sorted in increasing order and then rotated between 0 andnums.length − 1times.
Clarifying questions
What you would ask an interviewer before writing any code.