Check if an Array Was Sorted and Rotated
Problem
Print true if the array is a non-decreasing sorted array that was rotated some number of places (zero places also counts). Otherwise print false. Duplicates are allowed.
Constraints
- 1 <= n <= 10^5
Examples
Input
5 3 4 5 1 2
Output
true
Solutions
A sorted array has no fall around the circle. A rotation creates exactly one fall: the place where the biggest number meets the smallest. Two or more falls cannot come from a rotation.
/*
* Problem : Sorted and rotated?
* Input : n, then n integers.
* Output : true or false.
* Approach: Count the falls.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(int[] a) {
// Step 1: In a sorted and rotated array, going around the circle the numbers fall at most once.
int falls = 0;
for (int i = 0; i < a.length; i++) {
// Step 2: Compare each number with the next one. The last number is compared with the first.
if (a[i] > a[(i + 1) % a.length]) {
falls++;
}
}
return falls <= 1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (2)
- Why is the last number compared with the first?
- How many falls does [1, 2, 3] have around the circle?