Leetcode 1752. Check if Array Is Sorted and Rotated
You are given an array nums
of n
distinct integers. A permutation of the array is called a sorted and rotated if it is possible to rotate the array in such a way that it becomes non-decreasing.
Return true
if the array is sorted and rotated, otherwise return false
.
nums = [3, 4, 5, 1, 2]
true
[1, 2, 3, 4, 5]
is sorted and rotated by 3
positions to get [3, 4, 5, 1, 2]
.nums = [2, 1, 3, 4]
false
nums = [1, 2, 3]
true
[1, 2, 3]
is already non-decreasing.n
?
1 <= n <= 10^4
.To determine whether the array is sorted and rotated:
false
.#include <vector>
using namespace std;
bool check(vector<int>& nums) {
int count = 0; // To count the number of rotations
int n = nums.size();
for (int i = 0; i < n; ++i) {
// Check if there is a decrease in the order
if (nums[i] > nums[(i + 1) % n]) {
count++;
}
}
// Array is sorted and rotated if there is at most one decrease in the order
return count <= 1;
}
nums[i]
is greater than the next element nums[(i + 1) % n]
. Using modulo ensures that we seamlessly check the boundary condition from the last element to the first.count
is more than 1 at the end of the loop, it means there are multiple places where the sorted order is broken, thus the array is neither sorted nor properly rotated.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?