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
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 - Money Sums
You have N coins with certain values. Your task is to find all money sums you can create using these coins. Examples: Input: N = 4, coins[] = {4, 2, 5, 2}Output: 92 4 5 6 7 8 9 11 13Explanation: To create sum = 2, we can use the coin with value = 2.To create sum = 4, we can use both the coins with v
8 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 - 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 chessboard,
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"Input
4 min read
CSES Solutions - Coin Combinations I
Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ways you can produce a money sum X using the available coins. Examples: Input: N = 3, X = 9, coins[] = {2, 3, 5}Output: 8Explanation: There are 8 number of ways to
8 min read
Number of Transpositions in a Permutation
Cycle notation is a compact way to represent a permutation by breaking it down into cycles. A cycle represents a set of elements that are permuted (or swapped) among each other.Examples:Let us consider the permutation p = [5, 1, 4, 2, 3] of [1, 2, 3, 4, 5], the elements are moved as 1 â 5, 5 â 3, 3
6 min read
CSES Solutions - Coin Combinations II
Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ordered ways you can produce a money sum X using the available coins.Examples:Input: N = 3, X = 9, coins[] = {2, 3, 5}Output: 3Explanation: There are three ways to
8 min read