Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Arrange first N natural numbers such that absolute difference between all adjacent elements > 1?
We need to arrange the first N natural numbers such that the absolute difference between every two consecutive elements is greater than 1. If no such permutation exists, we return -1.
The approach uses a greedy strategy − arrange all odd numbers in descending order, followed by all even numbers in descending order. This ensures adjacent elements always differ by at least 2.
Syntax
void arrangeN(int N);
Algorithm
Begin if N is 1, then return 1 if N is 2 or 3, then return -1 as no such permutation exists even_max and odd_max is set as max even and odd number ? n arrange all odd numbers in descending order arrange all even numbers in descending order End
Example
Here's the complete C implementation of the arrangement algorithm −
#include <stdio.h>
void arrangeN(int N) {
if (N == 1) { // if N is 1, only that will be placed
printf("1");
return;
}
if (N == 2 || N == 3) { // for N = 2 and 3, no such permutation is available
printf("-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
printf("%d ", odd_max);
odd_max -= 2;
}
while (even_max >= 2) { // print all even numbers in decreasing order
printf("%d ", even_max);
even_max -= 2;
}
printf("<br>");
}
int main() {
int N = 8;
printf("Arrangement for N = %d: ", N);
arrangeN(N);
return 0;
}
Output
Arrangement for N = 8: 7 5 3 1 8 6 4 2
How It Works
- For N = 1: Only one element, so condition is satisfied.
- For N = 2, 3: No valid arrangement exists since consecutive numbers differ by 1.
- For N ? 4: Place odds in descending order (7,5,3,1), then evens in descending order (8,6,4,2).
- Adjacent elements always differ by at least 2: |7-5|=2, |5-3|=2, |1-8|=7, etc.
Conclusion
This greedy approach efficiently solves the problem by separating odd and even numbers. The arrangement ensures all adjacent pairs have an absolute difference greater than 1, making it a valid solution for N ? 4.
Advertisements
