Given an integer N. The task is to find the permutation of first N natural numbers such that the absolute difference between any two consecutive numbers > 1. If no such permutation is possible then print -1.
Input: N = 5
Output: 5 3 1 4 2
Input: N = 3
Approach: There may be many such arrangements possible but one of the most common and greedy approach is to arrange all odd numbers in decreasing (or increasing) order and after that arrange all even numbers in decreasing (or increasing) order. Note that if N = 3 or N = 2 then there will be no such arrangement possible and if N = 1 then the sequence will consist of a single element i.e. 1.
Below is the implementation of the above approach:
5 3 1 4 2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Split first N natural numbers into two sets with minimum absolute difference of their sums
- Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
- Check if permutation of first N natural numbers exists having Bitwise AND of adjacent elements non-zero
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K | Set 2
- Sort an Array based on the absolute difference of adjacent elements
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls
- Number of ways to arrange a word such that all vowels occur together
- Find the permutation of first N natural numbers such that sum of i % Pi is maximum possible
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Count array elements that can be maximized by adding any permutation of first N natural numbers
- Find all divisors of first N natural numbers
- Count elements in first Array with absolute difference greater than K with an element in second Array
- Maximize removal of adjacent array elements based on their absolute value
- Number of ways to arrange a word such that no vowels occur together
- Arrange the array such that upon performing given operations an increasing order is obtained
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Count possible combinations of pairs with adjacent elements from first N numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.