CSES Solutions - Permutations
Last Updated :
06 Aug, 2024
A permutation of integers 1,2 ... N is called beautiful if there are no adjacent elements whose difference is 1. Given N, construct a beautiful permutation if such a permutation exists. If there are no solutions, print "NO SOLUTION".
Examples:
Input: N = 5
Output: 4 2 5 3 1
Explanation: No two adjacent elements have a difference of 1.
Input: N = 3
Output: NO SOLUTION
Explanation: No permutation of size 3 is possible.
Approach: To solve the problem, follow the below idea:
The idea is to construct a beautiful permutation by first outputting all the even numbers up to n
and then all the odd numbers up to n
. This approach ensures that no two adjacent elements have a difference of 1, as even numbers have a difference of at least 2 from each other, and the same holds for odd numbers. For n=2 and n=3, there is no possible solution.
Proof of Correctness:
The correctness of the code can be proven by examining the characteristics of even and odd numbers. The solution can be proved using 3 cases:-
1. Even-Even Adjacent Pair: For even numbers, the difference between consecutive elements is always 2 (e.g., 2, 4, 6, ...). Therefore, if we print all even numbers first, no two even numbers will be adjacent with a difference of 1.
2. Odd-Odd Adjacent Pair: For odd numbers, the difference between consecutive elements is also always 2 (e.g., 1, 3, 5, ...). If we print all odd numbers after the even numbers, no two odd numbers will be adjacent with a difference of 1.
3. Even-Odd Adjacent Pair: We output all even numbers first and then all odd numbers, so there is one even-odd adjacent pair which consists of the greatest even number less than or equal to n
, and the first odd number will be 1. If the difference between these two numbers is greater than 1, then the permutation is valid, satisfying the conditions of a beautiful permutation. For n is greater than 3, the difference between the greatest even number less than or equal to n and the first odd number is always greater than 1, so our solution is correct. For n=2 or n=3, no permutation is possible.
Step-by-step algorithm:
- Check if
n
is 2 or 3. If so, it is not possible to construct a beautiful permutation, and "NO SOLUTION" is printed. Otherwise, - Iterate through all even numbers from 2 to
n
with a step size of 2 and print them. - Iterate through all odd numbers from 1 to
n
with a step size of 2 and print them.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to construct a beautiful permutation
void permutation(int N)
{
// Check if N is 2 or 3, as a beautiful permutation is
// not possible for these cases
if (N == 2 || N == 3) {
cout << "NO SOLUTION\n";
return;
}
// Output all even numbers first
for (int i = 2; i <= N; i = i + 2) {
// Print even numbers with a step of 2
cout << i << " ";
}
// Output all odd numbers next
for (int i = 1; i <= N; i = i + 2) {
// Print odd numbers with a step of 2
cout << i << " ";
}
}
// Driver Code
int main()
{
int N = 5;
// Call the permutation function with input N
permutation(N);
}
Java
public class BeautifulPermutation {
// Function to construct a beautiful permutation
public static void permutation(int N) {
// Check if N is 2 or 3, as a beautiful permutation is not possible for these cases
if (N == 2 || N == 3) {
System.out.println("NO SOLUTION");
return;
}
// Output all even numbers first
for (int i = 2; i <= N; i += 2) {
System.out.print(i + " ");
}
// Output all odd numbers next
for (int i = 1; i <= N; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int N = 5;
// Call the permutation function with input N
permutation(N);
}
}
Python
def permutation(N):
# Check if N is 2 or 3, as a beautiful permutation is not possible for these cases
if N == 2 or N == 3:
print("NO SOLUTION")
return
# Output all even numbers first
for i in range(2, N + 1, 2):
print(i)
# Output all odd numbers next
for i in range(1, N + 1, 2):
print(i)
# Driver Code
if __name__ == "__main__":
N = 5
# Call the permutation function with input N
permutation(N)
C#
using System;
class BeautifulPermutation
{
// Function to construct a beautiful permutation
static void Permutation(int N)
{
// Check if N is 2 or 3, as a beautiful permutation is not possible for these cases
if (N == 2 || N == 3)
{
Console.WriteLine("NO SOLUTION");
return;
}
// Output all even numbers first
for (int i = 2; i <= N; i += 2)
{
Console.Write(i + " ");
}
// Output all odd numbers next
for (int i = 1; i <= N; i += 2)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
public static void Main(string[] args)
{
int N = 5;
// Call the permutation function with input N
Permutation(N);
}
}
JavaScript
function permutation(N) {
// Check if N is 2 or 3, as a beautiful permutation is not possible for these cases
if (N === 2 || N === 3) {
console.log("NO SOLUTION");
return;
}
let result = '';
// Output all even numbers first
for (let i = 2; i <= N; i += 2) {
result += i + ' ';
}
// Output all odd numbers next
for (let i = 1; i <= N; i += 2) {
result += i + ' ';
}
console.log(result.trim());
}
// Driver Code
const N = 5;
// Call the permutation function with input N
permutation(N);
Time Complexity: O(N), where N is the size of permutation we have to construct.
Auxiliary Space: O(1)
Similar Reads
CSES Solutions - Permutation Inversions
Your task is to count the number of permutations of 1, 2, ⦠n that have exactly k inversions (i.e., pairs of elements in the wrong order). Examples: Input: n = 4, k = 3Output: 6Explanation: For n=4 and k=3, there are 6 permutations that satisfy the given conditions. The permutations are: [1, 4, 3, 2
4 min read
CSES Solutions - Array Description
You know that an array arr[] has N integers between 1 and M, and the absolute difference between two adjacent values is at most 1. Given a description of the array where some values may be unknown, your task is to count the number of arrays that match the description. Examples: Input: N = 3, M = 5,
14 min read
CSES Solutions - Coin Piles
You are given Q queries. In each query, you have two coin piles containing A and B coins. On each move, you can either remove one coin from the left pile and two coins from the right pile, or two coins from the left pile and one coin from the right pile. Your task is to efficiently find out if you c
7 min read
Permutations of given String
Given a string s, the task is to return all permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" Input: s
5 min read
CSES Solutions â Distributing Apples
There are n children and m apples that will be distributed to them. Your task is to count the number of ways this can be done. Examples: Input: n = 3, m = 2Output: 6Explanation: There are 6 ways to distribute 2 apples among 3 children: [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0] and [2, 0,
5 min read
CSES Solutions - Bit Strings
Your task is to calculate the number of bit strings of length N. For example, if N=3, the correct answer is 8, because the possible bit strings are 000, 001, 010, 011, 100, 101, 110, and 111. Print the result modulo 109+7. Examples: Input: N = 2Output: 4Explanation: There are total 4 bit strings pos
4 min read
CSES Solutions - Two Knights
Given a number N, the task is to count for each K = 1,2 ⦠N the number of ways two knights can be placed on a K X K chessboard so that they do not attack each other. Examples: Input: N = 2Output: 0 6Explanation: For a 1 X 1 chessboard, there is no possible way to place 2 knights on a 1 X 1 chessboar
7 min read
CSES Solutions - Letter Pair Move Game
There are 2n boxes in a line. Two adjacent boxes are empty, and all other boxes have a letter "A" or "B". Both letters appear in exactly n-1 boxes. Your task is to move the letters so that all letters "A" appear before any letter "B". On each turn you can choose any two adjacent boxes that have a le
13 min read
Permutations of a given string using STL
Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s = "XY"Output: "XY", "YX"
4 min read
CSES Solutions - Palindrome Reorder
Given a string S, your task is to reorder its letters in such a way that it becomes a palindrome (i.e., it reads the same forwards and backwards). Examples: Input: S = "AAAACACBA"Output: AAACBCAAAExplanation: We can reorder "AAAACACBA" to "AAACBCAAA" to get a palindrome string. Input: S = "AAABBB"Ou
6 min read