All Permutations of an Array
Last Updated :
10 Mar, 2025
Given an array arr[] the task is to print all the possible permutations of the given array.
Examples:
Input: arr[] = {1, 2, 3}
Output: {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 2, 1}, {3, 1, 2}
Explanation: There are 6 possible permutations
Input: arr[] = {1, 3}
Output: {1, 3}, {3, 1}
Explanation: There are 2 possible permutations
Approach: The task can be solved with the help of backtracking. A similar article for better understanding is here: Print all permutations of a given string

Below is the implementation of the above code:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the possible permutations.
// Initial value of idx is 0.
void permutations(vector<vector<int>>& res, vector<int> arr, int idx) {
// Base case: if idx reaches the size of the array,
// add the permutation to the result
if (idx == arr.size()) {
res.push_back(arr);
return;
}
// Permutations made by swapping each element
// starting from index `idx`
for (int i = idx; i < arr.size(); i++) {
// Swapping
swap(arr[idx], arr[i]);
// Recursive call to create permutations
// for the next element
permutations(res, arr, idx + 1);
// Backtracking
swap(arr[idx], arr[i]);
}
}
// Function to get the permutations
vector<vector<int>> permute(vector<int>& arr) {
// Declaring result variable
vector<vector<int>> res;
// Calling permutations with idx starting at 0
permutations(res, arr, 0);
return res;
}
// Driver Code
int main() {
vector<int> arr = { 1, 2, 3 };
vector<vector<int>> res = permute(arr);
// Printing result
for (auto x : res) {
for (auto y : x) {
cout << y << " ";
}
cout << endl;
}
return 0;
}
C
#include <stdio.h>
// Function to swap elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to find the possible permutations.
// Initial value of idx is 0.
void permutations(int res[][100], int* arr, int idx, int size, int* resSize) {
// Base case: if idx reaches the size of the array,
// add the permutation to the result
if (idx == size) {
for (int i = 0; i < size; i++) {
res[*resSize][i] = arr[i];
}
(*resSize)++;
return;
}
// Permutations made by swapping each element
// starting from index `idx`
for (int i = idx; i < size; i++) {
// Swapping
swap(&arr[idx], &arr[i]);
// Recursive call to create permutations
permutations(res, arr, idx + 1, size, resSize);
// Backtracking
swap(&arr[idx], &arr[i]);
}
}
// Function to get the permutations
void permute(int* arr, int size, int res[][100], int* resSize) {
permutations(res, arr, 0, size, resSize);
}
// Driver code
int main() {
int arr[] = { 1, 2, 3 };
int res[100][100]; // 2D array to store permutations
int resSize = 0;
permute(arr, 3, res, &resSize);
// Printing result
for (int i = 0; i < resSize; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find the possible permutations.
static void permutations(List<List<Integer>> res,
int[] arr, int idx) {
// Base case: if idx reaches the size of the array,
// add the permutation to the result
if (idx == arr.length) {
res.add(convertArrayToList(arr));
return;
}
// Permutations made by swapping each element
// starting from index `idx`
for (int i = idx; i < arr.length; i++) {
// Swapping
swap(arr, idx, i);
// Recursive call to create permutations
// for the next element
permutations(res, arr, idx + 1);
// Backtracking
swap(arr, idx, i);
}
}
// Function to get the permutations
static List<List<Integer>> permute(int[] arr) {
// Declaring result variable
List<List<Integer>> res = new ArrayList<>();
// Calling permutations with idx starting at 0
permutations(res, arr, 0);
return res;
}
// Helper method to swap elements in the array
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Helper method to convert array to list
static List<Integer> convertArrayToList(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int num : arr) {
list.add(num);
}
return list;
}
public static void main(String[] args) {
int[] arr = { 1, 2, 3 };
List<List<Integer>> res = permute(arr);
for (List<Integer> x : res) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Python
# Function to swap elements in the array
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
# Function to find the possible permutations.
# Initial value of idx is 0.
def permutations(res, arr, idx):
# Base case: if idx reaches the size of the array,
# add the permutation to the result
if idx == len(arr):
res.append(arr[:])
return
# Permutations made by swapping each element
for i in range(idx, len(arr)):
swap(arr, idx, i)
permutations(res, arr, idx + 1)
swap(arr, idx, i) # Backtracking
# Function to get the permutations
def permute(arr):
res = []
permutations(res, arr, 0)
return res
# Driver code
arr = [1, 2, 3]
res = permute(arr)
# Printing result
for perm in res:
print(" ".join(map(str, perm)))
C#
using System;
using System.Collections.Generic;
public class GfG {
// Function to swap elements in the array
private static void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Function to find the possible permutations.
// Initial value of idx is 0.
private static void Permutations(List<List<int>> res, int[] arr, int idx) {
if (idx == arr.Length) {
res.Add(new List<int>(arr));
return;
}
for (int i = idx; i < arr.Length; i++) {
Swap(arr, idx, i);
Permutations(res, arr, idx + 1);
Swap(arr, idx, i); // Backtracking
}
}
// Function to get the permutations
public static List<List<int>> Permute(int[] arr) {
List<List<int>> res = new List<List<int>>();
Permutations(res, arr, 0);
return res;
}
// Driver code
public static void Main() {
int[] arr = {1, 2, 3};
List<List<int>> res = Permute(arr);
// Printing result
foreach (List<int> perm in res) {
Console.WriteLine(string.Join(" ", perm));
}
}
}
JavaScript
// Function to swap elements in the array
function swap(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}
// Function to find the possible permutations.
// Initial value of idx is 0.
function permutations(res, arr, idx) {
if (idx === arr.length) {
res.push([...arr]);
return;
}
for (let i = idx; i < arr.length; i++) {
swap(arr, idx, i);
permutations(res, arr, idx + 1);
swap(arr, idx, i); // Backtracking
}
}
// Function to get the permutations
function permute(arr) {
const res = [];
permutations(res, arr, 0);
return res;
}
// Driver code
const arr = [1, 2, 3];
const res = permute(arr);
// Printing result
res.forEach(perm => {
console.log(perm.join(' '));
});
Output1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
Time Complexity: O(N*N!) Note that there are N! permutations and it requires O(N) time to print a permutation.
Auxiliary Space: O(N*N!)
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
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 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