Thursday, December 5, 2024
HomeSoftware DevelopmentGenerate a Permutation of 1 to N with no adjoining components distinction...

Generate a Permutation of 1 to N with no adjoining components distinction as 1

[ad_1]

Given an integer N, the duty is to assemble a permutation from 1 to N the place no adjoining components have distinction as 1. If there isn’t a such permutation print -1.

Permutation from 1 to N has all of the numbers from 1 to N current precisely as soon as.

Examples:

Enter: N = 5 
Output: 4 2 5 3 1
Rationalization: As for N = 5, [ 4 2 5 3 1 ] is the one permutation the place the distinction between the adjoining components just isn’t 1.

Enter: N = 3
Output: -1

Strategy: The issue may be solved based mostly on the next concept:

  • Distinction between any two even quantity is greater than 1 and equally, for all odd components their distinction is greater than 1
  • So, print all of the even numbers first adopted by the odd numbers.

Comply with the steps talked about beneath to implement the above method:

  • If N is lower than or equal to three, then no such permutation is feasible.
  • If N is even, print all even numbers from 2 to N firstly, after which all odds from 1 to N – 1 print all odd numbers.
  • If the N is odd then print all even numbers from 2 to N – 1 after which all odd numbers from 1 to N.

Under is the implementation of the above method:

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

vector<int> permutation(int n)

{

    vector<int> ans;

    if (n <= 3) {

        ans.push_back(-1);

    }

  

    

    if (n % 2 == 0) {

        for (int i = 2; i <= n; i += 2) {

            ans.push_back(i);

        }

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

            ans.push_back(i);

        }

    }

  

    

    else {

        for (int i = 2; i <= n - 1; i += 2) {

            ans.push_back(i);

        }

        for (int j = 1; j <= n; j += 2) {

            ans.push_back(j);

        }

    }

    return ans;

}

  

int primary()

{

    int N = 5;

    vector<int> ans = permutation(N);

    for (int x : ans)

        cout << x << " ";

    return 0;

}

Time complexity: O(N)
Auxiliary House: O(1)

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments