top of page
Search

Day 11 | Perfect Permutation | C++

  • Writer: Ayush Mahajan
    Ayush Mahajan
  • Aug 29, 2022
  • 1 min read

Today we will be solving Perfect Permutations. This is a very good question to solve your first problem on permutations.


I will be skipping the next question in the list, as they are straightforward. I have solved and mapped my implementation for them.

What exactly is a permutation?

Consider a list of numbers of size N. If we sort this list then, this list should be equivalent to {1,2,3,...,N}


In other words, the permutation of size N is the list of first N natural numbers in any order.


How to solve the problem?

Consider these mathematics:

Therefore, for any two i,j we need to just interchange them. And print them. I did that for adjacent pairs like (1,2), (3,4), and so on. Also notice, that we need even numbers so we can swap pairwise, thus if the input is odd, an answer is not possible.

Thus a simple for loop can serve as an answer here:

 for(int i = 1; i <= n; i += 2){
        cout << i+1 << ' ' << i << ' ';
    }

You can find my implementation here: C++ implementation



 
 
 

Comments


bottom of page