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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Sort an Array based on the absolute difference of adjacent elements
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Maximize removal of adjacent array elements based on their absolute value
- Maximum sum of difference of adjacent elements
- Count maximum elements of an array whose absolute difference does not exceed K
- Find K elements whose absolute difference with median of array is maximum
- Count possible combinations of pairs with adjacent elements from first N numbers
- Minimize the maximum difference between adjacent elements in an array
- Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal
- Rearrange array such that difference of adjacent elements is in descending order
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Replace elements with absolute difference of smallest element on left and largest element on right
- Count elements in first Array with absolute difference greater than K with an element in second Array
- Arrange given numbers to form the smallest number
- Arrange numbers to form a valid sequence
- Number of ways to arrange N numbers which are in a range from 1 to K under given constraints.
- Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
- Rearrange numbers in an array such that no two adjacent numbers are same
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.