Sorting Array with Two Swaps

Last Updated : 4 May, 2026

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.

Try It Yourself
redirect icon

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.

  • Count number of misplaced elements c
  • If c == 0, array is already sorted
  • If c == 3, it forms a cycle sortable in 2 swaps
  • If c == 4, try performing at most 2 swaps
  • For each swap, place element at its correct position
  • After swaps, check if array is sorted
  • Return true if sorted, else false
C++
#include <iostream>
#include <vector>
using namespace std;

// Function to count how many elements are not at correct position
int countUnsorted(vector<int>& a) {
    int c = 0;

    // Check each index
    for (int i = 0; i < a.size(); i++)
        if (a[i] != i + 1) // element not in correct position
            c++;

    return c;
}

bool checkSorted(vector<int> a) { 

    // Count misplaced elements
    int c = countUnsorted(a);

    // Case 1: already sorted OR one cycle of size 3
    if (c == 0 || c == 3)
        return true;

    // Case 2: possible 2 swaps needed
    if (c == 4) {

        // Perform at most 2 swaps
        for (int k = 0; k < 2; k++) {

            // Find first incorrect element
            for (int i = 0; i < a.size(); i++) {

                if (a[i] != i + 1) {

                    // Swap it with its correct position
                    swap(a[i], a[a[i] - 1]);
                    break; // only one swap per iteration
                }
            }
        }

        // Check if array is now sorted
        return countUnsorted(a) == 0;
    }

    // Other cases cannot be sorted in ≤ 2 swaps
    return false;
}

// Driver code
int main() {
    vector<int> arr = {4, 3, 2, 1};

    // Print result (true/false)
    cout << boolalpha << checkSorted(arr);

    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to count how many elements are not at correct position
    static int countUnsorted(List<Integer> a) {
        int c = 0;

        // Check each index
        for (int i = 0; i < a.size(); i++)
            if (a.get(i) != i + 1) // element not in correct position
                c++;

        return c;
    }

    static boolean checkSorted(List<Integer> a) {

        // Count misplaced elements
        int c = countUnsorted(a);

        // Case 1: already sorted OR one cycle of size 3
        if (c == 0 || c == 3)
            return true;

        // Case 2: possible 2 swaps needed
        if (c == 4) {

            // Perform at most 2 swaps
            for (int k = 0; k < 2; k++) {

                // Find first incorrect element
                for (int i = 0; i < a.size(); i++) {

                    if (a.get(i) != i + 1) {

                        // Swap it with its correct position
                        int temp = a.get(i);
                        a.set(i, a.get(temp - 1));
                        a.set(temp - 1, temp);
                        break; // only one swap per iteration
                    }
                }
            }

            // Check if array is now sorted
            return countUnsorted(a) == 0;
        }

        // Other cases cannot be sorted in ≤ 2 swaps
        return false;
    }

    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>(
            Arrays.asList(4, 3, 2, 1)
        );

        // Print result (true/false)
        System.out.println(checkSorted(arr));
    }
}
Python
class Solution:

    # Function to count how many elements are not at correct position
    @staticmethod
    def countUnsorted(a):
        c = 0

        # Check each index
        for i in range(len(a)):
            if a[i] != i + 1:  # element not in correct position
                c += 1

        return c

    @staticmethod
    def checkSorted(a):

        # Count misplaced elements
        c = Solution.countUnsorted(a)

        # Case 1: already sorted OR one cycle of size 3
        if c == 0 or c == 3:
            return True

        # Case 2: possible 2 swaps needed
        if c == 4:

            # Perform at most 2 swaps
            for k in range(2):

                # Find first incorrect element
                for i in range(len(a)):

                    if a[i] != i + 1:

                        # Swap it with its correct position
                        temp = a[i]
                        a[i] = a[temp - 1]
                        a[temp - 1] = temp
                        break  # only one swap per iteration

            # Check if array is now sorted
            return Solution.countUnsorted(a) == 0

        # Other cases cannot be sorted in ≤ 2 swaps
        return False

arr = [4, 3, 2, 1]

print(Solution.checkSorted(arr)) 
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to count how many elements are not at correct position
    static int countUnsorted(List<int> a) {
        int c = 0;

        // Check each index
        for (int i = 0; i < a.Count; i++)
            if (a[i] != i + 1) // element not in correct position
                c++;

        return c;
    }

    static bool checkSorted(List<int> a) {

        // Count misplaced elements
        int c = countUnsorted(a);

        // Case 1: already sorted OR one cycle of size 3
        if (c == 0 || c == 3)
            return true;

        // Case 2: possible 2 swaps needed
        if (c == 4) {

            // Perform at most 2 swaps
            for (int k = 0; k < 2; k++) {

                // Find first incorrect element
                for (int i = 0; i < a.Count; i++) {

                    if (a[i] != i + 1) {

                        // Swap it with its correct position
                        int temp = a[i];
                        a[i] = a[temp - 1];
                        a[temp - 1] = temp;
                        break; // only one swap per iteration
                    }
                }
            }

            // Check if array is now sorted
            return countUnsorted(a) == 0;
        }

        // Other cases cannot be sorted in ≤ 2 swaps
        return false;
    }

    static void Main() {
        List<int> arr = new List<int> { 4, 3, 2, 1 };

        // Print result (true/false)
        Console.WriteLine(checkSorted(arr));
    }
}
JavaScript
// Function to count how many elements are not at correct position
function countUnsorted(a) {
    let c = 0;

    // Check each index
    for (let i = 0; i < a.length; i++)
        if (a[i] !== i + 1) // element not in correct position
            c++;

    return c;
}

function checkSorted(a) {

    // Count misplaced elements
    let c = countUnsorted(a);

    // Case 1: already sorted OR one cycle of size 3
    if (c === 0 || c === 3)
        return true;

    // Case 2: possible 2 swaps needed
    if (c === 4) {

        // Perform at most 2 swaps
        for (let k = 0; k < 2; k++) {

            // Find first incorrect element
            for (let i = 0; i < a.length; i++) {

                if (a[i] !== i + 1) {

                    // Swap it with its correct position
                    let temp = a[i];
                    a[i] = a[temp - 1];
                    a[temp - 1] = temp;
                    break; // only one swap per iteration
                }
            }
        }

        // Check if array is now sorted
        return countUnsorted(a) === 0;
    }

    // Other cases cannot be sorted in ≤ 2 swaps
    return false;
}

// Driver code
let arr = [4, 3, 2, 1];

// Print result (true/false)
console.log(checkSorted(arr));

Output
true
Comment