Check if Array Is Sorted and Rotated

easy array rotation

Problem

You are given an integer array nums. Decide whether it could have been produced by taking some array sorted in non-decreasing order and rotating it: every element shifts right by the same offset and the tail wraps around to the front. A rotation by zero positions counts, and duplicate values are allowed (1 ≤ nums[i] ≤ 100).

Formally, return true exactly when there exist a sorted array B and an offset x with nums[i] = B[(i + x) mod n] for every index i.

Inputnums = [3, 4, 5, 1, 2]
Outputtrue
It is [1, 2, 3, 4, 5] rotated by 3: going around the circle there is exactly one drop, 5 → 1.

def check(nums):
    n = len(nums)
    count = 0
    for i in range(n):
        if nums[i] > nums[(i + 1) % n]:
            count += 1
    return count <= 1
function check(nums) {
  const n = nums.length;
  let count = 0;
  for (let i = 0; i < n; i++) {
    if (nums[i] > nums[(i + 1) % n]) count++;
  }
  return count <= 1;
}
boolean check(int[] nums) {
    int n = nums.length;
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (nums[i] > nums[(i + 1) % n]) count++;
    }
    return count <= 1;
}
bool check(vector<int>& nums) {
    int n = nums.size();
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (nums[i] > nums[(i + 1) % n]) count++;
    }
    return count <= 1;
}
Time: O(n) Space: O(1)