Given an array arr[] representing a permutation of first N natural numbers, the task is to find the lexicographically smallest permutation of the given array arr[] possible by swapping at most one pair of array elements. If it is not possible to make the array lexicographically smaller, then print “-1”.
Examples:
Input: arr[] = {3, 2, 1, 4}
Output: 1 2 3 4
Explanation: Swapping elements at index 2 and 0, the modified array is {1, 2, 3, 4}, which is lexicographically the smallest permutation of the given array arr[].Input: arr[] = {1, 2, 3, 4}
Output: -1
Approach: The idea is to find the first array element which is not at its correct position i.e., arr[i] is not the same as the index (i + 1), and swap it with the element at its correct position. Follow the steps below to solve this problem:
- Traverse the array arr[] and find the index i such that arr[i] is not equal to (i + 1), say idx, and store (i + 1) in a variable, say ele.
- Now, find the index of ele, say newIdx.
- After completing the above steps, there exists two indices idx and newIdx. The lexicographically smallest permutation of the array can be formed by swapping elements at indices idx and newIdx. Now, print the array arr[]. Otherwise, print “-1”.
Below is the implementation of the above approach:
Java
// Java program for the above approach import java.io.*; class GFG { // Function to print the // elements of the array arr[] static void print(int arr[]) { // Traverse the array arr[] for (int element : arr) { System.out.print(element + " "); } } // Function to convert given array to // lexicographically smallest permutation // possible by swapping at most one pair static void makeLexicographically( int arr[], int length) { // Stores the index of the first // element which is not at its // correct position int index = 0; int temp = 0; // Checks if any such array // element exists or not int check = 0; int condition = 0; int element = 0; // Traverse the given array for (int i = 0; i < length; ++i) { // If element is found at i if (element == arr[i]) { check = i; break; } // If the first array is // not in correct position else if (arr[i] != i + 1 && check == 0) { // Store the index of // the first elements index = i; check = 1; condition = -1; // Store the index of // the first element element = i + 1; } } // Swap the pairs if (condition == -1) { temp = arr[index]; arr[index] = arr[check]; arr[check] = temp; } // Print the array print(arr); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4 }; int N = arr.length; makeLexicographically(arr, N); } } |
1 2 3 4
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

