Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Easy
  • Last Updated : 01 May, 2021

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 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;
}

Java




// Java implementation of the above approach
import 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 permutation
function 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 permutation
function 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 Code
let 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)

This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :