- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We have the first N natural numbers. Our task is to get one permutation of them where the absolute difference between every two consecutive elements is > 1. If no such permutation is present, return -1.

The approach is simple. We will use the greedy approach. We will arrange all odd numbers in increasing or decreasing order, then arrange all even numbers in decreasing or increasing order

Begin if N is 1, then return 1 if N is 2 or 3, then return -1 as no such permutation is not present even_max and odd_max is set as max even and odd number less or equal to n arrange all odd numbers in descending order arrange all even numbers in descending order End

#include <iostream> using namespace std; void arrangeN(int N) { if (N == 1) { //if N is 1, only that will be placed cout << "1"; return; } if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available cout << "-1"; return; } int even_max = -1, odd_max = -1; //find max even and odd which are less than or equal to N if (N % 2 == 0) { even_max = N; odd_max = N - 1; } else { odd_max = N; even_max = N - 1; } while (odd_max >= 1) { //print all odd numbers in decreasing order cout << odd_max << " "; odd_max -= 2; } while (even_max >= 2) { //print all even numbers in decreasing order cout << even_max << " "; even_max -= 2; } } int main() { int N = 8; arrangeN(N); }

7 5 3 1 8 6 4 2

- Related Questions & Answers
- Count of all N digit numbers such that num + Rev(num) = 10^N - 1 in C++
- Average of first n even natural numbers?
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++
- Difference between sum of the squares of and square of sum first n natural numbers.
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in Python
- Find maximum number of elements such that their absolute difference is less than or equal to 1 in C++
- Absolute difference between the first X and last X Digits of N?
- Sum of all subsets of a set formed by first n natural numbers
- Sum of first n natural numbers in C Program
- Sum of square-sums of first n natural numbers
- Maximum sum such that no two elements are adjacent in C++
- Find permutation of first N natural numbers that satisfies the given condition in C++
- Print all increasing sequences of length k from first n natural numbers in C++
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M in Python

Advertisements