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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- 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
- Count maximum elements of an array whose absolute difference does not exceed K
- Maximum sum of difference of adjacent elements
- Minimize the maximum difference between adjacent elements in an array
- Rearrange array such that difference of adjacent elements is in descending order
- Count possible combinations of pairs with adjacent elements from first N numbers
- 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 numbers to form a valid sequence
- Arrange given numbers to form the smallest number
- Number of ways to arrange N numbers which are in a range from 1 to K under given constraints.
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.