What is a Permutation Array in DSA?
Last Updated :
30 Jul, 2024
A permutation array, often called a permutation or permuted array, is an arrangement of elements from a source array in a specific order different from their original placement.
The critical characteristic of a permutation array is that it contains all the elements from the source array but in a different order.
Imagine you have an array of elements, such as [1, 2, 3]
. A permutation of this array, like [3, 1, 2]
, represents a different order of the original elements.
How to Create a Permutation Array
Creating a permutation array involves rearranging the elements of a source array in a different order. Various methods and algorithms can be used to generate permutations, including recursive algorithms, iterative approaches, and mathematical techniques like the Lehmer code.
Here, we'll look at a simple example of how to create a permutation of a one-dimensional array using recursive approach.
Below is the implementation of the above idea:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function for swapping two numbers
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
// Function to find the possible
// permutations
void permutations(vector<vector<int> >& res,
vector<int> nums, int l, int h)
{
// Base case
// Add the vector to result and return
if (l == h) {
res.push_back(nums);
return;
}
// Permutations made
for (int i = l; i <= h; i++) {
// Swapping
swap(nums[l], nums[i]);
// Calling permutations for
// next greater value of l
permutations(res, nums, l + 1, h);
// Backtracking
swap(nums[l], nums[i]);
}
}
// Function to get the permutations
vector<vector<int> > permute(vector<int>& nums)
{
// Declaring result variable
vector<vector<int> > res;
int x = nums.size() - 1;
// Calling permutations for the first
// time by passing l
// as 0 and h = nums.size()-1
permutations(res, nums, 0, x);
return res;
}
// Driver Code
int main()
{
vector<int> nums = { 1, 2, 3 };
vector<vector<int> > res = permute(nums);
// printing result
for (auto x : res) {
for (auto y : x) {
cout << y << " ";
}
cout << endl;
}
return 0;
}
Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.Arrays;
public class GFG
{
// Function for swapping two numbers
static void swap(int nums[], int l, int i)
{
int temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
}
// Function to find the possible
// permutations
static void permutations(ArrayList<int[]> res,
int[] nums, int l, int h)
{
// Base case
// Add the array to result and return
if (l == h) {
res.add(Arrays.copyOf(nums, nums.length));
return;
}
// Permutations made
for (int i = l; i <= h; i++) {
// Swapping
swap(nums, l, i);
// Calling permutations for
// next greater value of l
permutations(res, nums, l + 1, h);
// Backtracking
swap(nums, l, i);
}
}
// Function to get the permutations
static ArrayList<int[]> permute(int[] nums)
{
// Declaring result variable
ArrayList<int[]> res = new ArrayList<int[]>();
int x = nums.length - 1;
// Calling permutations for the first
// time by passing l
// as 0 and h = nums.size()-1
permutations(res, nums, 0, x);
return res;
}
// Driver Code
public static void main(String[] args)
{
int[] nums = { 1, 2, 3 };
ArrayList<int[]> res = permute(nums);
// printing result
for (int[] x : res) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
// This code is contributed by jainlovely450
Python
# Python program for the above approach
# Function to find the possible
# permutations
def permutations(res, nums, l, h) :
# Base case
# Add the vector to result and return
if (l == h) :
res.append(nums);
for i in range(len(nums)):
print(nums[i], end=' ');
print('')
return;
# Permutations made
for i in range(l, h + 1):
# Swapping
temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
# Calling permutations for
# next greater value of l
permutations(res, nums, l + 1, h);
# Backtracking
temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
# Function to get the permutations
def permute(nums):
# Declaring result variable
x = len(nums) - 1;
res = [];
# Calling permutations for the first
# time by passing l
# as 0 and h = nums.size()-1
permutations(res, nums, 0, x);
return res;
# Driver Code
nums = [ 1, 2, 3 ];
res = permute(nums);
# This code is contributed by Saurabh Jaiswal
C#
using System;
using System.Collections.Generic;
class GFG
{
// Function for swapping two numbers
static void swap(int[] nums, int l, int i)
{
int temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
}
// Function to find the possible permutations
static void permutations(List<int[]> res, int[] nums, int l, int h)
{
// Base case: Add the array to result and return
if (l == h)
{
res.Add((int[])nums.Clone());
return;
}
// Permutations made
for (int i = l; i <= h; i++)
{
// Swapping
swap(nums, l, i);
// Calling permutations for next greater value of l
permutations(res, nums, l + 1, h);
// Backtracking
swap(nums, l, i);
}
}
// Function to get the permutations
static List<int[]> permute(int[] nums)
{
// Declaring result variable
List<int[]> res = new List<int[]>();
int x = nums.Length - 1;
// Calling permutations for the first time by passing l as 0 and h = nums.size()-1
permutations(res, nums, 0, x);
return res;
}
// Driver Code
static void Main(string[] args)
{
int[] nums = { 1, 2, 3 };
List<int[]> res = permute(nums);
// printing result
foreach (int[] x in res)
{
foreach (int y in x)
{
Console.Write(y + " ");
}
Console.WriteLine();
}
}
}
JavaScript
<script>
// JavaScript program for the above approach
// Function to find the possible
// permutations
function permutations(res, nums, l, h)
{
// Base case
// Add the vector to result and return
if (l == h)
{
res.push(nums);
for(let i = 0; i < nums.length; i++)
document.write(nums[i] + ' ');
document.write('<br>')
return;
}
// Permutations made
for(let i = l; i <= h; i++)
{
// Swapping
let temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
// Calling permutations for
// next greater value of l
permutations(res, nums, l + 1, h);
// Backtracking
temp = nums[l];
nums[l] = nums[i];
nums[i] = temp;
}
}
// Function to get the permutations
function permute(nums)
{
// Declaring result variable
let x = nums.length - 1;
let res = [];
// Calling permutations for the first
// time by passing l
// as 0 and h = nums.size()-1
permutations(res, nums, 0, x);
return res;
}
// Driver Code
let nums = [ 1, 2, 3 ];
let res = permute(nums);
// This code is contributed by Potta Lokesh
</script>
Output1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
Problems Based on Permutation Arrays
Problem | Post Link |
---|
Finding the kth permutation of an array | Read |
Inverting a permutation array | Read |
Reordering elements of an array based on a permutation | Read |
Sorting an array using a permutation array | Read |
Generating all permutations of an array | Read |
Finding the rank of a permutation within all permutations | Read |
Testing if two permutations are inverses of each other | Read |
Shuffling an array randomly using a permutation array | Read |
Permuting elements in a matrix based on row/column permutations | Read |
These problems involve various operations and applications related to permutation arrays, ranging from basic tasks like finding permutations to more complex operations such as inverting permutations or sorting using a permutation array.
Uses of Permutation Arrays
Permutation arrays find applications in a wide range of fields, including:
- Cryptography: permutations are used to create secure keys, encrypt data, and ensure the confidentiality and integrity of information.
- Game Development: Permutations are used in game development to randomize game elements, create random mazes, and introduce unpredictability to gameplay.
- Statistics and Sampling: permutation tests are employed to assess the significance of observed data and draw meaningful conclusions.
- Data Compression: Permutations play a role in data compression algorithms, helping reduce data size without significant loss of information.
Conclusion
Permutation arrays are a fundamental concept with a multitude of applications. Whether you're exploring combinatorial problems, securing data, or adding randomness to your projects, understanding permutations and their uses is essential in various domains of computer science and mathematics. Permutations provide the tools to rearrange and manipulate elements, offering creative solutions to an array of challenges.
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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 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