Practice › Arrays
Check if Sorted and Rotated
Easy · Arrays · Asked at Amazon, Microsoft, TCS, Infosys, Wipro
Print YES if the array could be obtained by taking an array sorted in non-decreasing order and rotating it some number of positions (possibly zero), otherwise NO.
Input
First line: n. Second line: n space-separated integers.
Output
YES or NO.
Constraints
- 1 ≤ n ≤ 10^5
- 1 ≤ a[i] ≤ 10^9
Count the places where a[i] > a[(i + 1) % n], comparing the last element with the first too. A sorted-then-rotated array has at most one such "drop".
Example 1
Input
5 3 4 5 1 2
Output
YES
Example 2
Input
4 2 1 3 4
Output
NO
Hints
- A sorted array has no place where a value is followed by a smaller one.
- Rotating it creates at most one such "drop" — where the end wraps to the start.
- Count the drops, including from the last element back to the first.
Approach
Count indices i with a[i] > a[(i + 1) % n]. A non-decreasing array rotated by any amount has at most one drop (at the rotation point; zero if every element is equal). Conversely, with at most one drop, rotating to start right after it gives a sorted array. So the answer is YES exactly when the count is ≤ 1.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
int drops = 0;
for (int i = 0; i < n; i++)
if (a[i] > a[(i + 1) % n]) drops++;
cout << (drops <= 1 ? "YES" : "NO") << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
drops = sum(1 for i in range(n) if a[i] > a[(i + 1) % n])
print("YES" if drops <= 1 else "NO")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
int drops = 0;
for (int i = 0; i < n; i++)
if (a[i] > a[(i + 1) % n]) drops++;
System.out.println(drops <= 1 ? "YES" : "NO");
}
}Solve Check if Sorted and Rotated online · All practice problems