1752. Check if Array Is Sorted and Rotated

#array

Check if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero).


Intuition

If the array is sorted then it will have 0 inversion, if a sorted array is rotated either clockwise or anti-clockwise direction the amount of inversion will be 1.

[1,2,3,4,5,6,7,8,9] => rotate clockwise 3 time => [7,8,9,1,2,3,4,5,6]
[1,2,3,4,5,6,7,8,9] => rotate anti-clockwise 3 time => [4,5,6,7,8,9,1,2,3]

Approach

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(n)\text{O}(n)

Code

 public boolean checkIfSortedAndRotated(int[] nums) {
    int countOfInversion = 0;
    for(int i = 0; i+1 < nums.length; ++i) {
      if(nums[i] > nums[i+1]) countOfInversion++;
    }
    
     return  countOfInversion == 0 || ( countOfInversion == 1 && nums[0] >= nums[nums.length-1] );
 }

Last updated