Different Ways to Generate Permutations of an Array
Last Updated :
23 Jul, 2025
Permutations are like the magic wand of combinatorics, allowing us to explore the countless ways elements can be rearranged within an array. Whether you're a coder, a math enthusiast, or someone on a quest to solve a complex problem, understanding how to generate all permutations of an array is a valuable skill. In this article, we are going the know Different Ways to Generate Permutations of an Array
What does Permutations of an Array Means?
Imagine you have three letters, A, B, and C, and you want to make words out of them. You can arrange them in different orders, and those arrangements are called permutations. Here are the possibilities: ABC, ACB, BAC, BCA, CBA, CAB. This is all about permutations, where order matters.
Now, the tricky part is that people sometimes use the term "combinations" when they mean permutations. But mathematically, there's a difference. Combinations are about picking things without caring about the order. For example, when rolling two dice and looking at the sum, it doesn't matter if you roll a 3 and a 4 or a 4 and a 3, the result is the same. That's a combination where order doesn't matter.
How Many Permutations Can Be Generated?
The number of permutations that can be generated from a set of elements depends on the size of the set/array. In combinatorics, the formula for calculating the number of permutations of a set of "n" distinct elements taken "r" at a time is given by:
P(n, r) = \frac{n!}{(n - r)!}
Where:
- P(n,r) represents the number of permutations.
- n is the total number of distinct elements.
- r is the number of elements taken at a time.
- n! (read as "n factorial") represents the product of all positive integers from 1 to n.
If you want to generate all permutations of a given set (where "r" is equal to "n"), the formula simplifies to:
P(n,n) = n!
So, for a set of "n" distinct elements, you can generate "n!" (n factorial) permutations. The number of permutations grows rapidly as "n" increases. For example, if you have 3 elements, there are 3! = 6 permutations, but if you have 4 elements, there are 4! = 24 permutations, and so on.
Examples:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Explanation: It generates all permutations of the elements in the vector (3!=6) i.e [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Explanation: It generates all permutations of the elements in the vector (2!=2) i.e [[0,1],[1,0]]
Input: nums = [1]
Output: [[1]]
Explanation: It generates all permutations of the elements in the vector (1!=1) i.e [[1]]
Different Ways to Generate Permutations of an Array:
- Simple Recursive Algorithm for Generating All Permutations of an Array
- Iterative Algorithm for Generating All Permutations of an Array
- Heap's Algorithm for Generating All Permutations of an Array
- Steinhaus Johnson Trotter Algorithm for Generating All Permutations of an Array
The simple recursive algorithm for generating all permutations of an array works like a branching tree. It starts with one element, explores all possible choices for the next element, and repeats this process for each subsequent element. This recursive "tree" expands until it covers all permutations, ensuring that no arrangement is missed. It's like systematically trying out different orders for the elements, gradually building each permutation, one step at a time.
Algorithm:
- To generate all the permutations of an array from index l to r, fix an element at index l and recur for the index l+1 to r.
- Backtrack and fix another element at index l and recur for index l+1 to r.
- Repeat the above steps to generate all the permutations.
Advantage:
- This algorithm is easy to understand and implement, making it accessible to programmers of all levels.
- It operates in-place, without the need for additional data structures, which can be memory-efficient.
- It can be quite efficient for small arrays, and in some cases, its performance may be adequate.
The iterative algorithm for generating permutations efficiently arranges array elements in a systematic order, avoiding the complexities of backtracking. It consistently creates the next lexicographically greater permutation and ensures complete coverage without needing to backtrack, making it a straightforward and efficient approach to generating all possible permutations.
Algorithm:
- Start with the original array.
- Use indices to keep track of the elements to permute.
- Repeat the following until there are no more permutations:
- Swap elements to generate the next permutation.
- Update the indices.
- Continue until all permutations are generated.
Advantage:
- Efficiency: It generates permutations in a predictable order without the need for backtracking, resulting in efficient and straightforward code.
- No Stack Overhead: Unlike recursive methods, it doesn't consume additional memory due to function call stacks, making it more memory-efficient.
Heaps algorithms are used to generate all the possible permutations of n-decimals of a number. This algorithm minimizes the movements, basically, it generates each permutation from the previous one by interchanging a single element while other elements are not disturbed.
Algorithm:
- Calculate all the possible permutations of the first N-1 digits adjoining the last element to each of these permutations.
- Iterate the digits, and check if N is an odd number then swap the first digit with the last digit and if N is an even number then swap the ith element with the last element.
- After repeating the above steps, Algorithm produces all the permutations of N.
Advantages:
- Heap's Algorithm is implemented using iteration, making it non-recursive.
- It generates permutations in-place, without requiring additional memory for data structures like stacks or recursion.
The Steinhaus Johnson Trotter algorithm's intuitive idea is to explore permutations by moving elements in a coordinated, directional manner. It ensures that every permutation is generated, and it can be particularly useful for problems where understanding the order of permutations is essential. The algorithm provides a different perspective on permutation generation compared to more traditional methods like Heap's Algorithm or recursive approaches.
The core idea is as follows:
- Directional Movement: The algorithm starts with an initial permutation, often in ascending order, and assigns a direction (left or right) to each element in the permutation.
- Mobile Element: A "mobile" element is defined as an element that can move in its current direction. It's larger than the element it's facing in its direction. Initially, the rightmost element is mobile.
- Swap and Flip: The algorithm performs a series of swaps between the mobile element and the adjacent element it's facing. After each swap, the direction of both elements is reversed.
- Iterative Process: This swapping and direction reversal process continues iteratively until there are no more mobile elements.
- Resulting Permutations: As the algorithm progresses, it generates permutations while maintaining a sense of movement and direction, creating a unique visual representation of permutations.
Advantages:
- Minimizes element swaps, reducing computational costs.
- Preserves inversion properties of permutations.
- Ideal for combinatorial and mathematical applications.
- No backtracking required, simplifying implementation.
- Memory-efficient.
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