Open In App

Lexicographically smallest permutation where no element is in original position

Improve
Improve
Like Article
Like
Save
Share
Report

Given a permutation of first N positive integers, the task is to form the lexicographically smallest permutation such that the new permutation does not have any element which is at the same index as of the old one. If it is impossible to make such permutation then print -1.

Examples:

Input: N = 5, arr[] = {1, 2, 3, 4, 5}
Output: 2 1 4 5 3 
Explanation: It is the smallest lexicographically permutation possible 
following the condition for 0 to N – 1 such that arr[i] != b[i].

Input: N = 1, arr[] = {1}
Output: -1

 

Brute Force Approach :

Below are the steps for brute force approach :

  • Generate all possible permutations of the given array.
  • Check each permutation for the condition that no element is at the same index as the old one.
  • Return the smallest lexicographically permutation that satisfies the condition.
  • If no such permutation exists, return -1.

Below is the code for above approach :

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the new permutation satisfies the condition
bool check(int arr[], int n, vector<int> &new_arr) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == new_arr[i]) {
            return false;
        }
    }
    return true;
}
 
// Function to generate all possible permutations
void generate_permutations(int arr[], int n, int index, vector<int>& perm, vector<bool>& used, vector<vector<int>>& permutations) {
    if (index == n) {
        permutations.push_back(perm);
        return;
    }
    for (int i = 0; i < n; i++) {
        if (!used[i]) {
            used[i] = true;
            perm.push_back(arr[i]);
            generate_permutations(arr, n, index+1, perm, used, permutations);
            perm.pop_back();
            used[i] = false;
        }
    }
}
 
// Function to find the lexicographically smallest permutation
void find_smallest_permutation(int arr[], int n) {
    vector<vector<int>> permutations;
    vector<bool> used(n, false);
    vector<int> perm;
    generate_permutations(arr, n, 0, perm, used, permutations);
    int smallest_index = -1;
    for (int i = 0; i < permutations.size(); i++) {
        if (check(arr, n, permutations[i])) {
            if (smallest_index == -1 || permutations[i] < permutations[smallest_index]) {
                smallest_index = i;
            }
        }
    }
    if (smallest_index == -1) {
        cout << "-1\n";
    }
    else {
        for (int i = 0; i < n; i++) {
            cout << permutations[smallest_index][i] << " ";
        }
        cout << "\n";
    }
}
 
// Driver code
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    find_smallest_permutation(arr, n);
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class SmallestPermutation {
    // Function to check if the new permutation satisfies the condition
    private static boolean check(int[] arr, int[] new_arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == new_arr[i]) {
                return false;
            }
        }
        return true;
    }
 
    // Function to generate all possible permutations
    private static void generatePermutations(int[] arr, int index, List<Integer> perm, boolean[] used, List<int[]> permutations) {
        if (index == arr.length) {
            int[] permArray = new int[arr.length];
            for (int i = 0; i < arr.length; i++) {
                permArray[i] = perm.get(i);
            }
            permutations.add(permArray);
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            if (!used[i]) {
                used[i] = true;
                perm.add(arr[i]);
                generatePermutations(arr, index + 1, perm, used, permutations);
                perm.remove(perm.size() - 1);
                used[i] = false;
            }
        }
    }
 
    // Function to find the lexicographically smallest permutation
    private static void findSmallestPermutation(int[] arr) {
        List<int[]> permutations = new ArrayList<>();
        boolean[] used = new boolean[arr.length];
        List<Integer> perm = new ArrayList<>();
        generatePermutations(arr, 0, perm, used, permutations);
        int smallestIndex = -1;
        for (int i = 0; i < permutations.size(); i++) {
            if (check(arr, permutations.get(i))) {
                if (smallestIndex == -1 || compareArrays(permutations.get(i), permutations.get(smallestIndex)) < 0) {
                    smallestIndex = i;
                }
            }
        }
        if (smallestIndex == -1) {
            System.out.println("-1");
        } else {
            for (int i = 0; i < arr.length; i++) {
                System.out.print(permutations.get(smallestIndex)[i] + " ");
            }
            System.out.println();
        }
    }
 
    // Function to compare two arrays lexicographically
    private static int compareArrays(int[] arr1, int[] arr2) {
        int n = Math.min(arr1.length, arr2.length);
        for (int i = 0; i < n; i++) {
            int cmp = Integer.compare(arr1[i], arr2[i]);
            if (cmp != 0) {
                return cmp;
            }
        }
        return Integer.compare(arr1.length, arr2.length);
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        findSmallestPermutation(arr);
    }
}


Python3




# Function to check if the new permutation satisfies the condition
def check(arr, n, new_arr):
    for i in range(n):
        if arr[i] == new_arr[i]:
            return False
    return True
 
# Function to generate all possible permutations
def generate_permutations(arr, n, index, perm, used, permutations):
    if index == n:
        permutations.append(perm.copy())
        return
    for i in range(n):
        if not used[i]:
            used[i] = True
            perm.append(arr[i])
            generate_permutations(arr, n, index + 1, perm, used, permutations)
            perm.pop()
            used[i] = False
 
# Function to find the lexicographically smallest permutation
def find_smallest_permutation(arr, n):
    permutations = []
    used = [False] * n
    perm = []
    generate_permutations(arr, n, 0, perm, used, permutations)
    smallest_index = -1
    for i in range(len(permutations)):
        if check(arr, n, permutations[i]):
            if smallest_index == -1 or permutations[i] < permutations[smallest_index]:
                smallest_index = i
    if smallest_index == -1:
        print("-1")
    else:
        for i in range(n):
            print(permutations[smallest_index][i], end=" ")
        print()
 
# Driver code
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    n = len(arr)
    find_smallest_permutation(arr, n)


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Function to check if the new permutation satisfies the condition
    static bool Check(int[] arr, int[] new_arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] == new_arr[i])
            {
                return false;
            }
        }
        return true;
    }
 
    // Function to generate all possible permutations
    static void GeneratePermutations(int[] arr, int index, List<int> perm, bool[] used, List<List<int>> permutations)
    {
        if (index == arr.Length)
        {
            permutations.Add(perm.ToList());
            return;
        }
 
        for (int i = 0; i < arr.Length; i++)
        {
            if (!used[i])
            {
                used[i] = true;
                perm.Add(arr[i]);
                GeneratePermutations(arr, index + 1, perm, used, permutations);
                perm.RemoveAt(perm.Count - 1);
                used[i] = false;
            }
        }
    }
 
    // Function to find the lexicographically smallest permutation
    static void FindSmallestPermutation(int[] arr)
    {
        List<List<int>> permutations = new List<List<int>>();
        bool[] used = new bool[arr.Length];
        List<int> perm = new List<int>();
        GeneratePermutations(arr, 0, perm, used, permutations);
 
        int smallestIndex = -1;
 
        for (int i = 0; i < permutations.Count; i++)
        {
            if (Check(arr, permutations[i].ToArray()))
            {
                if (smallestIndex == -1 || permutations[i].SequenceEqual(permutations[smallestIndex]))
                {
                    smallestIndex = i;
                }
            }
        }
 
        if (smallestIndex == -1)
        {
            Console.WriteLine("-1");
        }
        else
        {
            foreach (var num in permutations[smallestIndex])
            {
                Console.Write(num + " ");
            }
            Console.WriteLine();
        }
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        FindSmallestPermutation(arr);
    }
}


Javascript




// Function to check if the new permutation satisfies the condition
function check(arr, new_arr) {
    // Checks if the new permutation satisfies the condition
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === new_arr[i]) {
            return false; // If a value matches the original array, it's not a valid permutation
        }
    }
    return true; // All values in the new permutation are different from the original array
}
 
// Function to generate all possible permutations
function generatePermutations(arr, index, perm, used, permutations) {
    // Generates all possible permutations recursively
    if (index === arr.length) {
        permutations.push([...perm]); // Adds the generated permutation to the list of permutations
        return;
    }
    for (let i = 0; i < arr.length; i++) {
        if (!used[i]) {
            used[i] = true;
            perm.push(arr[i]); // Adds an element to the permutation
            generatePermutations(arr, index + 1, perm, used, permutations); // Recursive call to generate remaining permutations
            perm.pop(); // Backtracks and removes the last added element
            used[i] = false; // Marks the element as unused for the next iteration
        }
    }
}
 
// Function to find the lexicographically smallest permutation
function findSmallestPermutation(arr) {
    const permutations = []; // Array to store all permutations
    const used = new Array(arr.length).fill(false); // Array to track used elements in the permutation generation
    const perm = []; // Array to store individual permutations
 
    generatePermutations(arr, 0, perm, used, permutations); // Generates all possible permutations
 
    let smallestIndex = -1;
 
    // Find the smallest lexicographically valid permutation
    for (let i = 0; i < permutations.length; i++) {
        if (check(arr, permutations[i])) {
            if (smallestIndex === -1 || permutations[i] < permutations[smallestIndex]) {
                smallestIndex = i;
            }
        }
    }
 
    if (smallestIndex === -1) {
        console.log("-1"); // No valid permutation found
    } else {
        console.log(permutations[smallestIndex].join(' ')); // Prints the smallest valid permutation
    }
}
 
// Driver code
const arr = [1, 2, 3, 4, 5];
findSmallestPermutation(arr); // Call to find the smallest lexicographically valid permutation


Output

2 1 4 5 3 






Time Complexity : O(N*N !)

Space Complexity: O(N*N !)

Note :  The factorial complexity arises due to the number of possible permutations being n!, and we are generating all of them.

Another Approach: To solve the problem follow the below idea:

  • First, create the lexicographically smallest permutation and check if arr[i] is the same as b[i]. If it is not the last element, then swap, b[i] and b[i + 1].
  • If it is the last element then swap b[i] and b[i – 1] because there is no element in front of b[i] as it is the last element.

Follow the below steps to solve the problem:

  • First, create a vector b of size N from 1 to N.
  • Run a loop on vector b from index 0 to N – 1.
    • If the elements are different then continue.
    • Else if i is not N – 1, swap b[i] and b[i + 1]
    • If i is not 0 but it is the last element, swap b[i] and b[i – 1]
    • Otherwise, if it is the only element, then print -1.
  • After executing the loop print the vector b.

Below is the implementation of the above approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
#define ll long long
 
// Function to find lexicographically
// smallest permutation
void findPerm(int a[], int n)
{
 
    // Declare a vector of size n
    vector<ll> b(n);
 
    // Copy the vector a to b
    for (ll i = 0; i < n; i++) {
        b[i] = i + 1;
    }
 
    for (ll i = 0; i < n; i++) {
 
        // Elements are different
        if (a[i] != b[i])
            continue;
 
        // Elements are same
        if (i + 1 < n)
            swap(b[i], b[i + 1]);
        else if (i - 1 > 0)
            swap(b[i], b[i - 1]);
        else {
            cout << -1 << endl;
            return;
        }
    }
 
    // Print the lexicographically
    // smallest permutation
    for (ll i = 0; i < n; i++)
        cout << b[i] << " ";
 
    cout << endl;
}
 
// Driver Code
int main()
{
 
    int N = 5;
    int arr[] = { 1, 2, 3, 4, 5 };
 
    // Function call
    findPerm(arr, N);
    return 0;
}


Java




// Java code to implement the above approach
import java.io.*;
import java.util.*;
 
class GFG {
  // Function to find lexicographically
  // smallest permutation
  public static void findPerm(int a[], int n)
  {
 
    // Declare an array of size n
    int b[] = new int[n];
 
    // Copy the array a to b
    for (int i = 0; i < n; i++) {
      b[i] = i + 1;
    }
 
    for (int i = 0; i < n; i++) {
 
      // Elements are different
      if (a[i] != b[i])
        continue;
 
      // Elements are same
      if (i + 1 < n) {
        int temp = b[i];
        b[i] = b[i + 1];
        b[i + 1] = temp;
      }
      else if (i - 1 > 0) {
        int temp = b[i];
        b[i] = b[i - 1];
        b[i - 1] = temp;
      }
      else {
        System.out.println(-1);
        return;
      }
    }
 
    // Print the lexicographically
    // smallest permutation
    for (int i = 0; i < n; i++)
      System.out.print(b[i] + " ");
 
    System.out.println();
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 5;
    int arr[] = { 1, 2, 3, 4, 5 };
 
    // Function call
    findPerm(arr, N);
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# python3 code to implement the above approach
 
 
# Function to find lexicographically
# smallest permutation
def findPerm(a, n):
 
    # Declare a vector of size n
    b = [0 for _ in range(n)]
 
    # Copy the vector a to b
    for i in range(0, n):
        b[i] = i + 1
 
    for i in range(0, n):
 
        # Elements are different
        if (a[i] != b[i]):
            continue
 
        # Elements are same
        if (i + 1 < n):
            temp = b[i]
            b[i] = b[i+1]
            b[i+1] = temp
        elif (i - 1 > 0):
            temp = b[i]
            b[i] = b[i-1]
            b[i-1] = temp
        else:
            print(-1)
            return
 
    # Print the lexicographically
    # smallest permutation
    for i in range(0, n):
        print(b[i], end=" ")
 
    print()
 
 
# Driver Code
if __name__ == "__main__":
 
    N = 5
    arr = [1, 2, 3, 4, 5]
 
    # Function call
    findPerm(arr, N)
 
    # This code is contributed by rakeshsahni


C#




// C# code to implement the above approach
using System;
 
class GFG
{
 
  // Driver Code
  public static void Main(string[] args)
  {
    int N = 5;
    int[] arr = { 1, 2, 3, 4, 5 };
 
    // Function call
    findPerm(arr, N);
  }
 
  // Function to find lexicographically
  // smallest permutation
  public static void findPerm(int[] a, int n)
  {
    // Declare an array of size n
    int[] b = new int[n];
 
    // Copy the array a to b
    for (int i = 0; i < n; i++) {
      b[i] = i + 1;
    }
 
    for (int i = 0; i < n; i++) {
      // Elements are different
      if (a[i] != b[i])
        continue;
 
      // Elements are same
      if (i + 1 < n) {
        int temp = b[i];
        b[i] = b[i + 1];
        b[i + 1] = temp;
      }
      else if (i - 1 > 0) {
        int temp = b[i];
        b[i] = b[i - 1];
        b[i - 1] = temp;
      }
      else {
        Console.WriteLine(-1);
        return;
      }
    }
 
    // Print the lexicographically
    // smallest permutation
    for (int i = 0; i < n; i++)
      Console.Write(b[i] + " ");
    Console.WriteLine();
  }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




<script>
// Function to find lexicographically
// smallest permutation
function swat(a, b)
{
 
// create a temporary variable
a = a + b;
b = a - b;
a = a - b;
}
 
function findPerm(a, n)
{
 
    // Declare a array of size n
    let  b=new Array(n);
 
    // Copy the vector a to b
    for (let i = 0; i < n; i++) {
        b[i] = i + 1;
    }
 
    for (let i = 0; i < n; i++) {
 
        // Elements are different
        if (a[i] != b[i])
            continue;
 
        // Elements are same
        if (i + 1 < n)
            swat(b[i], b[i + 1]);
        else if (i - 1 > 0)
            swat(b[i], b[i - 1]);
        else {
            document.write(-1);
            document.write( "<br>");
            return;
        }
    }
 
    // Print the lexicographically
    // smallest permutation
    for (let i = 0; i < n; i++)
        document.write(b[i] + " ");
 
    document.write( "<br>");
}
 
// Driver Code
    let N = 5;
    let arr = [ 1, 2, 3, 4, 5 ];
 
    // Function call
    findPerm(arr, N);
     
    // This code is contributed by satwik4409.
   </script>


Output

2 1 4 5 3 





Time Complexity: O(N)
Auxiliary Space: O(N),



Last Updated : 09 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads