#K50147. One Swap Sorting
One Swap Sorting
One Swap Sorting
You are given T test cases. For each test case, you are given an integer N followed by a sequence of N integers. Your task is to determine if the given sequence can be sorted in non-decreasing order by performing at most one swap operation.
If the sequence is already sorted or it can be sorted by swapping exactly two elements, then print YES
. Otherwise, print NO
.
More formally, let \(A[1 \dots N]\) be the original sequence and \(B[1 \dots N]\) be the sorted sequence. The sequence can be sorted with at most one swap if and only if the number of indices \(i\) for which \(A[i] \neq B[i]\) is either 0 or 2.
inputFormat
The first line contains an integer T representing the number of test cases.
For each test case, the first line contains an integer N, the number of elements in the sequence. The second line contains N space-separated integers.
outputFormat
For each test case, output a single line containing YES
if the sequence can be sorted with at most one swap, and NO
otherwise.
3
4
1 3 5 3
5
4 5 2 1 6
2
2 1
YES
NO
YES
</p>