Lexicographically smallest permutation where no element is in original position
Last Updated :
09 Nov, 2023
Given a permutation of first N positive integers, the task is to form the lexicographically smallest permutation such that the new permutation does not have any element which is at the same index as of the old one. If it is impossible to make such permutation then print -1.
Examples:
Input: N = 5, arr[] = {1, 2, 3, 4, 5}
Output: 2 1 4 5 3
Explanation: It is the smallest lexicographically permutation possible
following the condition for 0 to N - 1 such that arr[i] != b[i].
Input: N = 1, arr[] = {1}
Output: -1
Brute Force Approach :
Below are the steps for brute force approach :
- Generate all possible permutations of the given array.
- Check each permutation for the condition that no element is at the same index as the old one.
- Return the smallest lexicographically permutation that satisfies the condition.
- If no such permutation exists, return -1.
Below is the code for above approach :
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if the new permutation satisfies the condition
bool check(int arr[], int n, vector<int> &new_arr) {
for (int i = 0; i < n; i++) {
if (arr[i] == new_arr[i]) {
return false;
}
}
return true;
}
// Function to generate all possible permutations
void generate_permutations(int arr[], int n, int index, vector<int>& perm, vector<bool>& used, vector<vector<int>>& permutations) {
if (index == n) {
permutations.push_back(perm);
return;
}
for (int i = 0; i < n; i++) {
if (!used[i]) {
used[i] = true;
perm.push_back(arr[i]);
generate_permutations(arr, n, index+1, perm, used, permutations);
perm.pop_back();
used[i] = false;
}
}
}
// Function to find the lexicographically smallest permutation
void find_smallest_permutation(int arr[], int n) {
vector<vector<int>> permutations;
vector<bool> used(n, false);
vector<int> perm;
generate_permutations(arr, n, 0, perm, used, permutations);
int smallest_index = -1;
for (int i = 0; i < permutations.size(); i++) {
if (check(arr, n, permutations[i])) {
if (smallest_index == -1 || permutations[i] < permutations[smallest_index]) {
smallest_index = i;
}
}
}
if (smallest_index == -1) {
cout << "-1\n";
}
else {
for (int i = 0; i < n; i++) {
cout << permutations[smallest_index][i] << " ";
}
cout << "\n";
}
}
// Driver code
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
find_smallest_permutation(arr, n);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class SmallestPermutation {
// Function to check if the new permutation satisfies the condition
private static boolean check(int[] arr, int[] new_arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == new_arr[i]) {
return false;
}
}
return true;
}
// Function to generate all possible permutations
private static void generatePermutations(int[] arr, int index, List<Integer> perm, boolean[] used, List<int[]> permutations) {
if (index == arr.length) {
int[] permArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
permArray[i] = perm.get(i);
}
permutations.add(permArray);
return;
}
for (int i = 0; i < arr.length; i++) {
if (!used[i]) {
used[i] = true;
perm.add(arr[i]);
generatePermutations(arr, index + 1, perm, used, permutations);
perm.remove(perm.size() - 1);
used[i] = false;
}
}
}
// Function to find the lexicographically smallest permutation
private static void findSmallestPermutation(int[] arr) {
List<int[]> permutations = new ArrayList<>();
boolean[] used = new boolean[arr.length];
List<Integer> perm = new ArrayList<>();
generatePermutations(arr, 0, perm, used, permutations);
int smallestIndex = -1;
for (int i = 0; i < permutations.size(); i++) {
if (check(arr, permutations.get(i))) {
if (smallestIndex == -1 || compareArrays(permutations.get(i), permutations.get(smallestIndex)) < 0) {
smallestIndex = i;
}
}
}
if (smallestIndex == -1) {
System.out.println("-1");
} else {
for (int i = 0; i < arr.length; i++) {
System.out.print(permutations.get(smallestIndex)[i] + " ");
}
System.out.println();
}
}
// Function to compare two arrays lexicographically
private static int compareArrays(int[] arr1, int[] arr2) {
int n = Math.min(arr1.length, arr2.length);
for (int i = 0; i < n; i++) {
int cmp = Integer.compare(arr1[i], arr2[i]);
if (cmp != 0) {
return cmp;
}
}
return Integer.compare(arr1.length, arr2.length);
}
// Driver code
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
findSmallestPermutation(arr);
}
}
Python3
# Function to check if the new permutation satisfies the condition
def check(arr, n, new_arr):
for i in range(n):
if arr[i] == new_arr[i]:
return False
return True
# Function to generate all possible permutations
def generate_permutations(arr, n, index, perm, used, permutations):
if index == n:
permutations.append(perm.copy())
return
for i in range(n):
if not used[i]:
used[i] = True
perm.append(arr[i])
generate_permutations(arr, n, index + 1, perm, used, permutations)
perm.pop()
used[i] = False
# Function to find the lexicographically smallest permutation
def find_smallest_permutation(arr, n):
permutations = []
used = [False] * n
perm = []
generate_permutations(arr, n, 0, perm, used, permutations)
smallest_index = -1
for i in range(len(permutations)):
if check(arr, n, permutations[i]):
if smallest_index == -1 or permutations[i] < permutations[smallest_index]:
smallest_index = i
if smallest_index == -1:
print("-1")
else:
for i in range(n):
print(permutations[smallest_index][i], end=" ")
print()
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5]
n = len(arr)
find_smallest_permutation(arr, n)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to check if the new permutation satisfies the condition
static bool Check(int[] arr, int[] new_arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == new_arr[i])
{
return false;
}
}
return true;
}
// Function to generate all possible permutations
static void GeneratePermutations(int[] arr, int index, List<int> perm, bool[] used, List<List<int>> permutations)
{
if (index == arr.Length)
{
permutations.Add(perm.ToList());
return;
}
for (int i = 0; i < arr.Length; i++)
{
if (!used[i])
{
used[i] = true;
perm.Add(arr[i]);
GeneratePermutations(arr, index + 1, perm, used, permutations);
perm.RemoveAt(perm.Count - 1);
used[i] = false;
}
}
}
// Function to find the lexicographically smallest permutation
static void FindSmallestPermutation(int[] arr)
{
List<List<int>> permutations = new List<List<int>>();
bool[] used = new bool[arr.Length];
List<int> perm = new List<int>();
GeneratePermutations(arr, 0, perm, used, permutations);
int smallestIndex = -1;
for (int i = 0; i < permutations.Count; i++)
{
if (Check(arr, permutations[i].ToArray()))
{
if (smallestIndex == -1 || permutations[i].SequenceEqual(permutations[smallestIndex]))
{
smallestIndex = i;
}
}
}
if (smallestIndex == -1)
{
Console.WriteLine("-1");
}
else
{
foreach (var num in permutations[smallestIndex])
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
// Driver code
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
FindSmallestPermutation(arr);
}
}
JavaScript
// Function to check if the new permutation satisfies the condition
function check(arr, new_arr) {
// Checks if the new permutation satisfies the condition
for (let i = 0; i < arr.length; i++) {
if (arr[i] === new_arr[i]) {
return false; // If a value matches the original array, it's not a valid permutation
}
}
return true; // All values in the new permutation are different from the original array
}
// Function to generate all possible permutations
function generatePermutations(arr, index, perm, used, permutations) {
// Generates all possible permutations recursively
if (index === arr.length) {
permutations.push([...perm]); // Adds the generated permutation to the list of permutations
return;
}
for (let i = 0; i < arr.length; i++) {
if (!used[i]) {
used[i] = true;
perm.push(arr[i]); // Adds an element to the permutation
generatePermutations(arr, index + 1, perm, used, permutations); // Recursive call to generate remaining permutations
perm.pop(); // Backtracks and removes the last added element
used[i] = false; // Marks the element as unused for the next iteration
}
}
}
// Function to find the lexicographically smallest permutation
function findSmallestPermutation(arr) {
const permutations = []; // Array to store all permutations
const used = new Array(arr.length).fill(false); // Array to track used elements in the permutation generation
const perm = []; // Array to store individual permutations
generatePermutations(arr, 0, perm, used, permutations); // Generates all possible permutations
let smallestIndex = -1;
// Find the smallest lexicographically valid permutation
for (let i = 0; i < permutations.length; i++) {
if (check(arr, permutations[i])) {
if (smallestIndex === -1 || permutations[i] < permutations[smallestIndex]) {
smallestIndex = i;
}
}
}
if (smallestIndex === -1) {
console.log("-1"); // No valid permutation found
} else {
console.log(permutations[smallestIndex].join(' ')); // Prints the smallest valid permutation
}
}
// Driver code
const arr = [1, 2, 3, 4, 5];
findSmallestPermutation(arr); // Call to find the smallest lexicographically valid permutation
Time Complexity : O(N*N !)
Space Complexity: O(N*N !)
Note : The factorial complexity arises due to the number of possible permutations being n!, and we are generating all of them.
Another Approach: To solve the problem follow the below idea:
- First, create the lexicographically smallest permutation and check if arr[i] is the same as b[i]. If it is not the last element, then swap, b[i] and b[i + 1].
- If it is the last element then swap b[i] and b[i - 1] because there is no element in front of b[i] as it is the last element.
Follow the below steps to solve the problem:
- First, create a vector b of size N from 1 to N.
- Run a loop on vector b from index 0 to N - 1.
- If the elements are different then continue.
- Else if i is not N - 1, swap b[i] and b[i + 1]
- If i is not 0 but it is the last element, swap b[i] and b[i - 1]
- Otherwise, if it is the only element, then print -1.
- After executing the loop print the vector b.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
// Function to find lexicographically
// smallest permutation
void findPerm(int a[], int n)
{
// Declare a vector of size n
vector<ll> b(n);
// Copy the vector a to b
for (ll i = 0; i < n; i++) {
b[i] = i + 1;
}
for (ll i = 0; i < n; i++) {
// Elements are different
if (a[i] != b[i])
continue;
// Elements are same
if (i + 1 < n)
swap(b[i], b[i + 1]);
else if (i - 1 > 0)
swap(b[i], b[i - 1]);
else {
cout << -1 << endl;
return;
}
}
// Print the lexicographically
// smallest permutation
for (ll i = 0; i < n; i++)
cout << b[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int N = 5;
int arr[] = { 1, 2, 3, 4, 5 };
// Function call
findPerm(arr, N);
return 0;
}
Java
// Java code to implement the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find lexicographically
// smallest permutation
public static void findPerm(int a[], int n)
{
// Declare an array of size n
int b[] = new int[n];
// Copy the array a to b
for (int i = 0; i < n; i++) {
b[i] = i + 1;
}
for (int i = 0; i < n; i++) {
// Elements are different
if (a[i] != b[i])
continue;
// Elements are same
if (i + 1 < n) {
int temp = b[i];
b[i] = b[i + 1];
b[i + 1] = temp;
}
else if (i - 1 > 0) {
int temp = b[i];
b[i] = b[i - 1];
b[i - 1] = temp;
}
else {
System.out.println(-1);
return;
}
}
// Print the lexicographically
// smallest permutation
for (int i = 0; i < n; i++)
System.out.print(b[i] + " ");
System.out.println();
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
int arr[] = { 1, 2, 3, 4, 5 };
// Function call
findPerm(arr, N);
}
}
// This code is contributed by Rohit Pradhan
Python3
# python3 code to implement the above approach
# Function to find lexicographically
# smallest permutation
def findPerm(a, n):
# Declare a vector of size n
b = [0 for _ in range(n)]
# Copy the vector a to b
for i in range(0, n):
b[i] = i + 1
for i in range(0, n):
# Elements are different
if (a[i] != b[i]):
continue
# Elements are same
if (i + 1 < n):
temp = b[i]
b[i] = b[i+1]
b[i+1] = temp
elif (i - 1 > 0):
temp = b[i]
b[i] = b[i-1]
b[i-1] = temp
else:
print(-1)
return
# Print the lexicographically
# smallest permutation
for i in range(0, n):
print(b[i], end=" ")
print()
# Driver Code
if __name__ == "__main__":
N = 5
arr = [1, 2, 3, 4, 5]
# Function call
findPerm(arr, N)
# This code is contributed by rakeshsahni
C#
// C# code to implement the above approach
using System;
class GFG
{
// Driver Code
public static void Main(string[] args)
{
int N = 5;
int[] arr = { 1, 2, 3, 4, 5 };
// Function call
findPerm(arr, N);
}
// Function to find lexicographically
// smallest permutation
public static void findPerm(int[] a, int n)
{
// Declare an array of size n
int[] b = new int[n];
// Copy the array a to b
for (int i = 0; i < n; i++) {
b[i] = i + 1;
}
for (int i = 0; i < n; i++) {
// Elements are different
if (a[i] != b[i])
continue;
// Elements are same
if (i + 1 < n) {
int temp = b[i];
b[i] = b[i + 1];
b[i + 1] = temp;
}
else if (i - 1 > 0) {
int temp = b[i];
b[i] = b[i - 1];
b[i - 1] = temp;
}
else {
Console.WriteLine(-1);
return;
}
}
// Print the lexicographically
// smallest permutation
for (int i = 0; i < n; i++)
Console.Write(b[i] + " ");
Console.WriteLine();
}
}
// This code is contributed by Tapesh(tapeshdua420)
JavaScript
<script>
// Function to find lexicographically
// smallest permutation
function swat(a, b)
{
// create a temporary variable
a = a + b;
b = a - b;
a = a - b;
}
function findPerm(a, n)
{
// Declare a array of size n
let b=new Array(n);
// Copy the vector a to b
for (let i = 0; i < n; i++) {
b[i] = i + 1;
}
for (let i = 0; i < n; i++) {
// Elements are different
if (a[i] != b[i])
continue;
// Elements are same
if (i + 1 < n)
swat(b[i], b[i + 1]);
else if (i - 1 > 0)
swat(b[i], b[i - 1]);
else {
document.write(-1);
document.write( "<br>");
return;
}
}
// Print the lexicographically
// smallest permutation
for (let i = 0; i < n; i++)
document.write(b[i] + " ");
document.write( "<br>");
}
// Driver Code
let N = 5;
let arr = [ 1, 2, 3, 4, 5 ];
// Function call
findPerm(arr, N);
// This code is contributed by satwik4409.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N),
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem