Given a positive integer N, the task is to construct a permutation of first N natural numbers such that the absolute difference between adjacent elements is either 2, 3, or 4. If it is not possible to construct such a permutation, then print “-1”.
Examples:
Input: N = 4
Output: 3 1 4 2
Explanation:
Consider a permutation {3, 1, 4, 2}. Now, the absolute difference between adjacent elements are {2, 3, 2}.
Input: N = 9
Output: 9 7 5 3 1 4 2 6 8
Approach: The given problem can be solved by grouping up consecutive even and odd elements together to construct the permutation. Follow the steps below to solve the problem:
- If the value of N is less than 4 then print -1 as it is impossible to construct a permutation according to the given conditions for N less than 4.
- Initialize a variable, say i as N, and perform the following steps below:
- If the value of i is even, then decrement the value of i by 1.
- Iterate until the value of i is at least 1 and print the value of i and decrement the value of i by 2.
- Print 4 and 2 and update the value of i to 6.
- Iterate in the range [i, N] and print the value of i and increment the value of i by 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void getPermutation( int N)
{
if (N <= 3) {
cout << -1;
return ;
}
int i = N;
if (N % 2 == 0)
i--;
while (i >= 1) {
cout << i << " " ;
i -= 2;
}
cout << 4 << " " << 2 << " " ;
i = 6;
while (i <= N) {
cout << i << " " ;
i += 2;
}
}
int main()
{
int N = 9;
getPermutation(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void getPermutation( int N)
{
if (N <= 3 )
{
System.out.print(- 1 );
return ;
}
int i = N;
if (N % 2 == 0 )
i--;
while (i >= 1 )
{
System.out.print(i + " " );
i -= 2 ;
}
System.out.print( 4 + " " + 2 + " " );
i = 6 ;
while (i <= N)
{
System.out.print(i + " " );
i += 2 ;
}
}
public static void main(String[] args)
{
int N = 9 ;
getPermutation(N);
}
}
|
Python3
def getPermutation(N):
if (N < = 3 ):
print ( - 1 )
return
i = N
if (N % 2 = = 0 ):
i - = 1
while (i > = 1 ):
print (i, end = " " )
i - = 2
print ( 4 , 2 , end = " " )
i = 6
while (i < = N):
print ( i, end = " " )
i + = 2
if __name__ = = '__main__' :
N = 9
getPermutation(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void getPermutation( int N)
{
if (N <= 3)
{
Console.Write(-1);
return ;
}
int i = N;
if (N % 2 == 0)
i--;
while (i >= 1)
{
Console.Write(i + " " );
i -= 2;
}
Console.Write(4 + " " + 2 + " " );
i = 6;
while (i <= N)
{
Console.Write(i + " " );
i += 2;
}
}
public static void Main()
{
int N = 9;
getPermutation(N);
}
}
|
Javascript
<script>
function getPermutation(N)
{
if (N <= 3)
{
document.write(-1);
return ;
}
let i = N;
if (N % 2 == 0)
i--;
while (i >= 1)
{
document.write(i + " " );
i -= 2;
}
document.write(4 + " " + 2 + " " );
i = 6;
while (i <= N)
{
document.write(i + " " );
i += 2;
}
}
let N = 9;
getPermutation(N);
</script>
|
Output: 9 7 5 3 1 4 2 6 8
Time Complexity: O(N)
Auxiliary Space: O(1)