VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-smallest-permutation-where-no-element-is-in-original-position/

⇱ Lexicographically smallest permutation where no element is in original position - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically smallest permutation where no element is in original position

Last Updated : 9 Nov, 2023

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 :


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:


Output
2 1 4 5 3 

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

Comment