Pseudo Sorted Array Codechef Solution
An array A of length N is said to be pseudo-sorted if it can be made non-decreasing after performing the following operation at most once. Choose an i such that 1≤i≤N−1 and swap Ai and Ai+1 Given an array A, determine if it is pseudo-sorted or not.
- The first line contains a single integer T – the number of test cases. Then the test cases follow.
- The first line of each test case contains an integer N – the size of the array A.
- The second line of each test case contains N space-separated integers A1,A2,…,AN denoting the array A.
- For each testcase, output YES if the array A is pseudo-sorted, NO otherwise.
- You may print each character of YES and NO in uppercase or lowercase (for example, yes, yEs, Yes will be considered identical).
- Sum of N over all test cases do not exceed 2⋅105
Sample Input 1
3 5 7 8 9
1 3 2 3
3 2 1
Sample Output 1
- Test case 1: The array is already sorted in non-decreasing order.
- Test case 2: We can choose i=2 and swap A2 and A3. The resulting array will be [1,2,3,3], which is sorted in non-decreasing order.
- Test case 3: It can be proven that the array cannot be sorted in non-decreasing order in at most one operation.
Program: Pseudo Sorted Array Codechef Solution in Python
for _ in range(int(input())): n=int(input()) t=0 tmp=0 l=list(map(int,input().split())) for i in range(n): if l[i-1]>l[i] and i>=1: tmp=l[i-1] l[i-1]=l[i] l[i]=tmp if l[i-2] > l[i-1] and i>=2: t+=2 else: t+=1 if t<2: print("YES") else: print("NO")