Find out how many times the array is rotated

Pattern: Binary search on rotated arrays

medium

Rotating a sorted array right k times moves its smallest value to index k. So the number of rotations is the index of the minimum, found with the same search as Find Minimum.

The problem

A sorted array of different values was rotated to the right k times, with 0 ≤ k < n. Each right rotation moves the last value to the front. Return k. For example, [3, 4, 5, 1, 2] gives 3 and [4, 5, 6, 7, 0, 1, 2, 3] gives 4. A sorted array gives 0.

The function name findKRotation matches the takeUforward practice page. Use the link above for the exact statement and limits. The values are different, as that page says.

Think first

  • In the original sorted array, where is the smallest value?
  • After one right rotation, where is it? After k?
  • Which earlier problem finds that position?

Hints

    Brute force, and why it fails

    Find the index of the smallest value with a scan: O(n). Or find the one index where a value is bigger than the next. Binary search is O(log n).

    The key insight

    "How far was it rotated" and "where is the minimum" are the same question. Recognising that lets one template answer both.

    Dry run

    30lo
    41 
    52 
    13 
    24hi

    nums = [3, 4, 5, 1, 2]. Started from [1, 2, 3, 4, 5], each right rotation moved the 1 one step right.

    Step 1 of 3

    The plan

    lo = 0, hi = n - 1
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if nums[mid] > nums[hi]: lo = mid + 1
        else: hi = mid
    return lo
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Same as Find Minimum.

    Edge cases

    • Not rotated: 0.
    • Rotated n - 1 times, as in [2, 3, 4, 5, 1]: 4.
    • One value: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int findKRotation(int[] nums) {
            int lo = 0, hi = nums.length - 1;       // the number of rotations is the index of the minimum
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] > nums[hi]) lo = mid + 1;
                else hi = mid;
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        int findKRotation(vector<int>& nums) {
            int lo = 0, hi = static_cast<int>(nums.size()) - 1;   // the number of rotations is the index of the minimum
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] > nums[hi]) lo = mid + 1;
                else hi = mid;
            }
            return lo;
        }
    };

    Python

    class Solution:
        def findKRotation(self, nums: list[int]) -> int:
            lo, hi = 0, len(nums) - 1               # the number of rotations is the index of the minimum
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] > nums[hi]:
                    lo = mid + 1
                else:
                    hi = mid
            return lo

    Common mistakes

    • Returning the minimum value instead of its index.
    • Counting left rotations, which gives n - k instead of k (except when k is 0).
    • Using it on arrays with repeated values without the extra care from Search in Rotated Sorted Array II.

    Similar problems