DEV Community

shipra Shankhwar
shipra Shankhwar

Posted on

Leetcode QOTD:- 1752. Check if Array Is Sorted and Rotated

  1. Traverse the array and compare every element with the next element.
  2. Use (i + 1) % nums.length so the last element can also compare with the first element.
  3. In a sorted and rotated array, there can be only one position where: nums[i] > nums[i + 1]
  4. Count such positions using didGetRotated. If count becomes greater than 1, return false; otherwise return true because the array is sorted and rotated at most once.
class Solution {
    public boolean check(int[] nums) {
        int didGetRotated = 0;
        int rotateInd = 0;
        for (int i = 0; i < nums.length; i++) {
            if ((nums[i] > nums[(i + 1)%nums.length]) && ++didGetRotated > 1) {
                return false;
            }
        }
        return didGetRotated <= 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
xiaoming_nian_94953c8c9b8 profile image
Andy Nian

The modulo trick with (i + 1) % nums.length is neat for wrapping around to the start of the array, but I'm curious how this works with larger datasets, especially if there's noise in how the array got 'rotated'. Sometimes it seems like LeetCode patterns don't always match real-world scenarios. I've been using PracHub for different OA question sets, and they really get the follow-up questions that feel closer to actual recruiter challenges. The key is understanding the implications of these rotations.