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 implementation of the above program is given below. Â
C++
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the permutationvoid 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 Codeint main(){Â Â Â Â long long int n = 9;Â Â Â Â findPermutation(n);Â Â Â Â return 0;} |
Java
// Java implementation of the above approachimport java.util.Vector;Â
class GFG {Â
// Function to print the permutation    static void findPermutation(int n) {        Vector<Integer> res = new Vector<Integer>();Â
        // 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.add(en);                    en += 2;                } else {                    res.add(on);                    on += 2;                }            }        } // If n is odd        else {            for (int i = 0; i < n - 2; i++) {                if (i % 2 == 0) {                    res.add(en);                    en += 2;                } else {                    res.add(on);                    on += 2;                }            }            res.add(n);            res.add(n - 2);        }Â
        // Print result        for (int i = 0; i < n; i++) {            System.out.print(res.get(i) + " ");        }        System.out.println("");    }Â
// Driver Code    public static void main(String[] args) {        int n = 9;        findPermutation(n);    }}// This code is contributed by PrinciRaj1992 |
Python3
# Python3 implementation of the above approachÂ
# Function to print the permutation def findPermutation(n) :Â
    res = []Â
    # Initial numbers to be pushed to result     en, on = 2, 1Â
    # If n is even     if (n % 2 == 0) :        for i in range(n) :             if (i % 2 == 0) :                 res.append(en)                en += 2            else :                res.append(on)                 on += 2          Â
    # If n is odd     else :         for i in range(n-2) :            if (i % 2 == 0) :                 res.append(en)                 en += 2            else :                 res.append(on)                on += 2                               res.append(n)        res.append(n - 2)       Â
    # Print result     for i in range(n) :        print(res[i] ,end = " ")        print() Â
Â
# Driver Code if __name__ == "__main__" :Â Â Â Â Â Â n = 9; Â Â Â Â findPermutation(n) Â
# This code is contributed by Ryuga |
C#
// C# implementation of the above approach using System;using System.Collections;public class GFG { Â
// Function to print the permutation     static void findPermutation(int n) {         ArrayList res = new ArrayList(); Â
        // 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.Add(en);                     en += 2;                 } else {                     res.Add(on);                     on += 2;                 }             }         } // If n is odd         else {             for (int i = 0; i < n - 2; i++) {                 if (i % 2 == 0) {                     res.Add(en);                     en += 2;                 } else {                     res.Add(on);                     on += 2;                 }             }             res.Add(n);             res.Add(n - 2);         } Â
        // Print result         for (int i = 0; i < n; i++) {             Console.Write(res[i] + " ");         }         Console.WriteLine("");     } Â
// Driver Code     public static void Main() {         int n = 9;         findPermutation(n);     } } // This code is contributed by 29AjayKumar |
PHP
<?php // PHP implementation of the above approachÂ
// Function to print the permutationfunction findPermutation($n){Â Â Â Â $res = array(); Â
    // Initial numbers to be pushed     // to result    $en = 2;    $on = 1; Â
    // If n is even    if ($n % 2 == 0)    {        for ($i = 0; $i < $n; $i++)         {            if (i % 2 == 0)             {                array_push($res, $en);                $en += 2;            } else            {                array_push($res, $on);                $on += 2;            }        }    } Â
    // If n is odd    else    {        for ($i = 0; $i < $n - 2; $i++)         {            if ($i % 2 == 0)             {                array_push($res, $en);                $en += 2;            }             else            {                array_push($res, $on);                $on += 2;            }        }        array_push($res, $n);        array_push($res, $n - 2);    }Â
    // Print result    for ($i = 0; $i < $n; $i++)         echo $res[$i] . " ";     echo "\n";}Â
// Driver Code$n = 9;findPermutation($n);Â
// This code is contributed by ita_c?> |
Javascript
<script>Â
// Javascript implementation of the above approachÂ
// Function to print the permutationfunction findPermutation(n){    let res = [];         // Initial numbers to be pushed to result    let en = 2, on = 1;Â
    // If n is even    if (n % 2 == 0)    {        for(let i = 0; i < n; i++)         {            if (i % 2 == 0)             {                res.push(en);                en += 2;            }             else            {                res.push(on);                on += 2;            }        }    }     // If n is odd    else    {        for(let i = 0; i < n - 2; i++)         {            if (i % 2 == 0)             {                res.push(en);                en += 2;            }             else            {                res.push(on);                on += 2;            }        }        res.push(n);        res.push(n - 2);    }Â
    // Print result    for(let i = 0; i < n; i++)    {        document.write(res[i] + " ");    }    document.write("");}Â
// Driver Codelet n = 9;Â
findPermutation(n);Â
// This code is contributed by avanitrachhadiya2155Â
</script> |
Output:Â
2 1 4 3 6 5 8 9 7
Time Complexity: O(n), where n is the given positive integer.
Auxiliary Space: O(n), where n is the given positive integer.
This article is contributed by Sarthak Kohli. If you like zambiatek and would like to contribute, you can also write an article using write.zambiatek.com or mail your article to review-team@zambiatek.com. See your article appearing on the zambiatek 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.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



