#K72542. Nearly Sorted Array
Nearly Sorted Array
Nearly Sorted Array
Given an array of distinct integers, determine if the array is nearly sorted. An array is considered nearly sorted if every element's position in the sorted order differs by at most 1 from its current position. Formally, let \( sorted \) be the array sorted in increasing order. For each index \( i \) (0-indexed), the condition
\(|index(sorted, a_i) - i| \le 1\)
must hold. If this condition is satisfied for every element, print "YES"; otherwise, print "NO".
inputFormat
The input begins with an integer \( T \) representing the number of test cases. Each test case consists of two lines: the first line contains an integer \( N \) denoting the number of elements in the array, and the second line contains \( N \) space-separated integers.
outputFormat
For each test case, output a single line with "YES" if the array is nearly sorted, otherwise output "NO".
## sample3
5
1 3 2 4 5
4
4 3 2 1
5
2 1 3 4 5
YES
NO
YES
</p>