![]() |
VOOZH | about |
Given an array a[] that represents a permutation of the n numbers, the task is to determine if it's possible to sort the array using two swaps. If it is not possible return false otherwise return true.
Examples:
Input: a[] = [4, 3, 2, 1]
Output: true
Explanation: Swap(a[1], a[4]), now a[] = [1, 3, 2, 4], Swap(a[2], a[3]), now a[] = [1, 2, 3, 4]Input: a[] = [4, 3, 1, 2]
Output: false
Explanation: It's not possible to sort the array in two swaps.
We count how many elements are not in their correct positions (i.e.,
a[i] != i+1). Based on this count, we determine whether the array can be sorted using at most 2 swaps. If needed, we simulate up to 2 swaps and check if the array becomes sorted.
cc == 0, array is already sorted c == 3, it forms a cycle sortable in 2 swaps c == 4, try performing at most 2 swaps true