Lexicographically smallest permutation of {1, .. n} such that no. and position do not match

Given a positive integer n, find the lexicographically smallest permutation p of {1, 2, .. n} such that pi != i. i.e., i should not be there at i-th position where i varies from 1 to n.

Examples:

Input : 5
Output : 2 1 4 5 3
Consider the two permutations that follow
the requirement that position and numbers
should not be same.
p = (2, 1, 4, 5, 3) and q = (2, 4, 1, 5, 3).  
Since p is lexicographically smaller, our 
output is p.

Input  : 6
Output : 2 1 4 3 6 5

Since we need lexicographically smallest (and 1 cannot come at position 1), we put 2 at first position. After 2, we put the next smallest element i.e., 1. After that the next smallest considering it does not violates our condition of pi != i.
Now, if our n is even we simply take two variables one which will contain our count of even numbers and one which will contain our count of odd numbers and then we will keep them adding in the vector till we reach n.
But, if our n is odd, we do the same task till we reach n-1 because if we add till n then in the end we will end up having pi = i. So when we reach n-1, we first add n to the position n-1 and then on position n we will put n-2.
The C++ implementation of the above program is given below.

#include <bits/stdc++.h>
using namespace std;

// Function to print the permutation
void findPermutation(vector<int> a, int n)
{
    vector<int> res;   

    // Initial numbers to be pushed to result
    int en = 2, on = 1; 

    // If n is even
    if (n % 2 == 0) {
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                res.push_back(en);
                en += 2;
            } else {
                res.push_back(on);
                on += 2;
            }
        }
    } 

    // If n is odd
    else {
        for (int i = 0; i < n - 2; i++) {
            if (i % 2 == 0) {
                res.push_back(en);
                en += 2;
            } else {
                res.push_back(on);
                on += 2;
            }
        }
        res.push_back(n);
        res.push_back(n - 2);
    }

    // Print result
    for (int i = 0; i < n; i++) 
        cout << res[i] << " ";    
    cout << "\n";
}

// Driver Code
int main()
{
    long long int n = 9;
    findPermutation(n);
    return 0;
}

Output:

2 1 4 3 6 5 8 9 7

This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.