Permutations of an Array in lexicographical order.
Last Updated :
29 Sep, 2023
Given an array arr[] of distinct integers, the task is to print all the possible permutations in lexicographical order.
Examples:
Input: arr = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Input: arr = [1, 2]
Output: [[1, 2], [2, 1]]
Input: arr = [1]
Output: [[1]]
Approach: To solve the problem follow the below idea:
- In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting.
- This problem can be solved using Backtracking. We swap the ith index with all indexes after ith index and this way recursively we can generate all the permutaions.
Steps to solve the problem:
- Sort the input array initially.
- We define a recursive function with parameters as the ith index at which we have to take decisions and a given array.
- Here we have two options: not to Right rotate from the ith index to another index after i and to Rotate it with other indexes after i.
- Run a loop from (i+1,n) denoted by j and Right rotate the segment arr[i...j] and make the recursive call for (i + 1)th index then Left rotate the segment arr[i...j] to undo the changes of the Right rotate to restore the array to the original configuration.
- Base case: if we are at the end of the array then we can print the array and return.
Why rotation of elements works to generate permutations in lexicographical order:
Consider arr = [1, 2, 3],
- If we swap arr[0] with arr[2] it becomes [3, 2, 1] :
- Now we are taking a decision for arr[1] element, we have two choices:
- If we do not swap arr[1] with arr[2] then arr = [3, 2, 1]
- If we swap arr[1] with arr[2] then arr = [3, 1, 2]
- We observed here is [3, 2, 1] appears before [3, 1, 2] which is not the case of lexicographical order. But, if we Right rotate arr[0...2] then arr becomes [3, 1, 2], by rotating sorted order of elements remained conserved and with this elements get swapped automatically:
- Now we are taking a decision for arr[1] element, we have two choices:
- If we do not swap arr[1] with arr[2] then arr = [3, 1, 2]
- If we swap arr[1] with arr[2] then arr = [3, 2, 1]
- Now [3, 1, 2] appears before [3, 2, 1], this is lexicographical order.
Below is the code for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to right rotate the segement
// arr[i....j] of arr
void RightRotate(int arr[], int i, int j)
{
int temp = arr[j];
for (int k = j; k > i; k--) {
arr[k] = arr[k - 1];
}
arr[i] = temp;
}
// Function to Left rotate the segement
// arr[i....j] of arr
void LeftRotate(int arr[], int i, int j)
{
int temp = arr[i];
for (int k = i; k < j; k++) {
arr[k] = arr[k + 1];
}
arr[j] = temp;
}
void PrintPermutations(int arr[], int i, int n)
{
// Base case if i reaches end of the
// array and there is no element
// to swap with
if (i == n - 1) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return;
}
// If do not rotate any segement
// starting from i+1th index
PrintPermutations(arr, i + 1, n);
// If we rotate segement then we can have
// rotation of segement arr[i....j]
for (int j = i + 1; j < n; j++) {
RightRotate(arr, i, j);
PrintPermutations(arr, i + 1, n);
LeftRotate(arr, i, j);
}
}
/// Drivers code
int main()
{
int arr[] = { 2, 1, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + N);
// Function Call
cout << "Permutations are below" << endl;
PrintPermutations(arr, 0, N);
return 0;
}
Java
// Java code for the above approach
import java.util.Arrays;
class GFG {
// Function to right rotate the segement
// arr[i....j] of arr
static void RightRotate(int arr[], int i, int j) {
int temp = arr[j];
for (int k = j; k > i; k--) {
arr[k] = arr[k - 1];
}
arr[i] = temp;
}
// Function to Left rotate the segement
// arr[i....j] of arr
static void LeftRotate(int arr[], int i, int j) {
int temp = arr[i];
for (int k = i; k < j; k++) {
arr[k] = arr[k + 1];
}
arr[j] = temp;
}
static void PrintPermutations(int arr[], int i, int n) {
// Base case if i reaches end of the
// array and there is no element
// to swap with
if (i == n - 1) {
for (int k = 0; k < n; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
return;
}
// If do not rotate any segement
// starting from i+1th index
PrintPermutations(arr, i + 1, n);
// If we rotate segement then we can have
// rotation of segement arr[i....j]
for (int j = i + 1; j < n; j++) {
RightRotate(arr, i, j);
PrintPermutations(arr, i + 1, n);
LeftRotate(arr, i, j);
}
}
// Drivers code
public static void main(String[] args) {
int arr[] = { 2, 1, 3 };
int N = arr.length;
Arrays.sort(arr);
// Function Call
System.out.println("Permutations are below");
PrintPermutations(arr, 0, N);
}
}
// This code is contributed by Sakshi
Python3
# Python code for the above approach
def right_rotate(arr, i, j):
temp = arr[j]
for k in range(j, i, -1):
arr[k] = arr[k - 1]
arr[i] = temp
def left_rotate(arr, i, j):
temp = arr[i]
for k in range(i, j):
arr[k] = arr[k + 1]
arr[j] = temp
def print_permutations(arr, i, n):
# Base case: if i reaches the end of the array
# and there is no element to swap with
if i == n - 1:
print(*arr)
return
# If we do not rotate any segment starting from the (i+1)th index
print_permutations(arr, i + 1, n)
# If we rotate a segment, then we can have rotation of segment arr[i....j]
for j in range(i + 1, n):
right_rotate(arr, i, j)
print_permutations(arr, i + 1, n)
left_rotate(arr, i, j)
# Driver code
if __name__ == "__main__":
arr = [2, 1, 3]
N = len(arr)
arr.sort()
# Function Call
print("Permutations are below:")
print_permutations(arr, 0, N)
#This Code is Contributed by chinmaya121221
C#
using System;
class Program
{
// Function to right rotate the segment arr[i....j] of arr
static void RightRotate(int[] arr, int i, int j)
{
int temp = arr[j];
for (int k = j; k > i; k--)
{
arr[k] = arr[k - 1];
}
arr[i] = temp;
}
// Function to left rotate the segment arr[i....j] of arr
static void LeftRotate(int[] arr, int i, int j)
{
int temp = arr[i];
for (int k = i; k < j; k++)
{
arr[k] = arr[k + 1];
}
arr[j] = temp;
}
// Function to print permutations of the array
static void PrintPermutations(int[] arr, int i, int n)
{
// Base case: if i reaches the end of the array and there are no elements to swap with
if (i == n - 1)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
return;
}
// If we do not rotate any segment starting from the i+1th index
PrintPermutations(arr, i + 1, n);
// If we rotate a segment, we can have rotations of the segment arr[i....j]
for (int j = i + 1; j < n; j++)
{
RightRotate(arr, i, j);
PrintPermutations(arr, i + 1, n);
LeftRotate(arr, i, j);
}
}
// Driver code
static void Main()
{
int[] arr = { 2, 1, 3 };
int N = arr.Length;
// Sort the array
Array.Sort(arr);
// Function Call
Console.WriteLine("Permutations are below:");
PrintPermutations(arr, 0, N);
}
}
JavaScript
// Function to right rotate the segment arr[i....j] of arr
function rightRotate(arr, i, j) {
const temp = arr[j];
for (let k = j; k > i; k--) {
arr[k] = arr[k - 1];
}
arr[i] = temp;
}
// Function to left rotate the segment arr[i....j] of arr
function leftRotate(arr, i, j) {
const temp = arr[i];
for (let k = i; k < j; k++) {
arr[k] = arr[k + 1];
}
arr[j] = temp;
}
// Function to print permutations of the array
function printPermutations(arr, i, n) {
// Base case: if i reaches the end of the array and there are no elements to swap with
if (i === n - 1) {
console.log(arr.join(" "));
return;
}
// If we do not rotate any segment starting from the i+1th index
printPermutations(arr, i + 1, n);
// If we rotate a segment, we can have rotations of the segment arr[i....j]
for (let j = i + 1; j < n; j++) {
rightRotate(arr, i, j);
printPermutations(arr, i + 1, n);
leftRotate(arr, i, j);
}
}
// Driver code
function main() {
const arr = [2, 1, 3];
const N = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
// Function Call
console.log("Permutations are below:");
printPermutations(arr, 0, N);
}
// Call the main function
main();
OutputPermutations are below
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Time Complexity: O(N*N!)
Auxillary space: O(N), where N is the number of elements in the array.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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