![]() |
VOOZH | about |
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 :
Below is the code for above approach :
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:
Below is the implementation of the above approach:
2 1 4 5 3
Time Complexity: O(N)
Auxiliary Space: O(N),