[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++
|
Time complexity: O(N)
Auxiliary House: O(1)
[ad_2]