LeetCode Entry
1752. Check if Array Is Sorted and Rotated
Is array sorted and rotated?
1752. Check if Array Is Sorted and Rotated easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/883
Problem TLDR
Is array sorted and rotated? #easy
Intuition
Count of violations must be less than 2.
Approach
- check ‘<’ condition instead of ‘>=’ to avoid the corner cases
- let’s golf
Complexity
-
Time complexity: \(O(n)\), O(n^2) for Kotlin’s solution
-
Space complexity: \(O(1)\), O(n^2) for Kotlin
Code
fun check(n: IntArray) =
n.sorted() in n.indices.map { n.drop(it) + n.take(it) }
pub fn check(n: Vec<i32>) -> bool {
(0..n.len()).filter(|&i| n[i] > n[(i + 1) % n.len()]).count() < 2
}
bool check(vector<int>& n) {
int c = 0, m = size(n);
for (int i = 0; i < m; c += n[i] > n[++i % m]);
return c < 2;
}