[LeetCode] Check if Array Is Sorted and Rotated

1752. Check if Array Is Sorted and Rotated

Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

There may be duplicates in the original array.

Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool check(vector<int>& nums) {
int ok = 0;
for(int i = 0, n = nums.size(); i < n and ok <= 1; i++) {
ok += nums[(i - 1 + n) % n] > nums[i];
}
return ok <= 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/02/PS/LeetCode/check-if-array-is-sorted-and-rotated/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.