Given an integer n, the task is to generate a permutation if exists, of distinct integers in the range 1 <= integers <= n such that no two adjacent elements have difference as 1 , otherwise print -1.
Example :
Input : 4 Output : 2 4 1 3 Explanation : In the above output the difference between any two adjacent elements is greater than 1. Input : 6 Output : 1 3 5 2 4 6 Explanation : No two adjacent elements have difference equal to 1. Input : 3 Output : -1
Approach :
The main observation of the problem is that for n greater than 3 , such permutation always exists .
To solve the above problem follow these steps:
1. If n is less than or equal to 3 then print -1
2. If n is equal to 4 then print the permutation “2 4 1 3” itself.
3. If n is greater than 4 then
1. Iterate from i = 1 and go till n , print i and increment it by +2 in each iteration.
2. Iterate from i = 2 and go till n , print i and increment it by +2 in each iteration.
Implementation :
// c++ program to generate a
// permutation of n integers
// with no two adjacent elements
// having difference 1
#include <bits/stdc++.h>
using namespace std;
void generatePermutation(int n)
{
// base conditions
if (n <= 3)
cout << -1;
else if (n == 4)
cout << "2 4 1 3";
// main cases
else {
// iterate from i = 1 and go till n
// incrementing it by 2
for (int i = 1; i <= n; i += 2)
cout << i << " ";
// iterate from i = 2 and go till n
// incrementing i by +2
for (int i = 2; i <= n; i += 2)
cout << i << " ";
}
}
int main()
{
// input element
int n = 10;
// call the function
// generatePermutation.
generatePermutation(n);
return 0;
}
Complexity Analysis :
Time Complexity : O(n) because we use two loop for a single passes.
Space Complexity : O(1)