Java 100% Faster Solution Explained
Complexity
Time complexity: O(N)
Space complexity: O(1)
Code
# Complexity
- Time complexity: O(N)
- Space complexity: O(1)

# Code
```java []
class Solution {
    public int minimumRightShifts(List<Integer> nums) {
        int id = 0, min = 100;
        for (int i = 0; i < nums.size(); i++) {
            if (min > nums.get(i)) {
                id = i;
                min = nums.get(i);
            }
        }
        int idx = id, count = 1, prev = nums.get(idx++);
        while (count++ < nums.size()) {
            if (nums.get(idx % nums.size()) < prev) return -1;
            prev = nums.get(idx++ % nums.size());
        }
        return (nums.size() - id) % nums.size();
    }
}
```
``` Java-comments []
class Solution {
    public int minimumRightShifts(List<Integer> nums) {
        // Initialize variables:
        // 'id' stores the index of the minimum element
        // 'min' stores the minimum value found so far, initialized to a large number
        int id = 0, min = 100;

        // Find the index of the minimum element in the list
        for (int i = 0; i < nums.size(); i++) {
            if (min > nums.get(i)) {
                id = i;
                min = nums.get(i);
            }
        }

        // Start checking from the minimum element's index
        int idx = id;
        int count = 1;                    // Counter for how many elements we've checked
        int prev = nums.get(idx++);      // Store the first element (minimum) and move index forward

        // Traverse the list once in circular fashion starting from the minimum element
        while (count++ < nums.size()) {
            // If the current element is less than the previous, it's not sorted — return -1
            if (nums.get(idx % nums.size()) < prev) return -1;

            // Update previous to current and move forward
            prev = nums.get(idx++ % nums.size());
        }

        // If valid rotated sorted array, calculate how many right shifts were needed
        // For example, if the minimum element is at index 2 in a size-5 array,
        // it took (5 - 2) % 5 = 3 right shifts to bring it to the start
        return (nums.size() - id) % nums.size();
    }
}
```
['Java']