permutations
string manipulation
algorithms
combinatorics
programming

Listing all permutations of a string/integer

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Permutations are a fundamental concept in mathematics and computer science. The permutation of a set is a rearrangement of its elements. In the context of strings or integers, it involves rearranging the characters or digits to form new combinations. Understanding how to generate permutations is essential for various applications, such as solving puzzles, generating test cases, or optimizing algorithms.

Technical Explanation

Definition and Mathematical Background

A permutation is any arrangement of a set of objects. Mathematically, if a set has nn elements, it has n!n! (n factorial) permutations. This factor represents the product of all positive integers from 1 through nn. For example, if you have a set of three elements {A, B, C}, the number of permutations is 3!=3×2×1=63! = 3 × 2 × 1 = 6.

Algorithm Overview

To list all permutations of a string or integer:

  1. Recursive Approach:
    • Choose a character from the string (or digit from an integer).
    • Recursively generate permutations of the remaining characters.
    • Append the chosen character to each permutation obtained from the recursive step.
  2. Iterative Approach:
    • Use an iterative method such as the Heap's Algorithm, which is particularly efficient for generating permutations in a systematic way.
  3. Backtracking Approach:
    • Use a decision tree to explore permutations by swapping elements, ensuring no duplicates are generated.

Complexity

The time complexity of generating permutations is O(n!)O(n!), which is factorial in nature. Space complexity can be O(n)O(n) for storing the elements in a permutation.

Examples

Example 1: String Permutations

Consider the string "ABC". The permutations would be:

  • ABC
  • ACB
  • BAC
  • BCA
  • CAB
  • CBA

Here's a step-by-step breakdown using the recursive method:

  1. Fix 'A', permute BC to get BC, CB.
  2. Fix 'B', permute AC to get AC, CA.
  3. Fix 'C', permute AB to get AB, BA.

Example 2: Integer Permutations

For the integer 123, the approach is identical to a string. The permutations are:

  • 123
  • 132
  • 213
  • 231
  • 312
  • 321

Recursive Code Implementation

Below is a Python implementation using the recursive method:

python
1def permute(elements):
2    if len(elements) == 0:
3        return []
4    if len(elements) == 1:
5        return [elements]
6    
7    perms = []
8    for i in range(len(elements)):
9        current = elements[i]
10        remaining_list = elements[:i] + elements[i+1:]
11        
12        for p in permute(remaining_list):
13            perms.append([current] + p)
14    return perms
15
16# Example usage:
17perms = permute(['A', 'B', 'C'])
18for perm in perms:
19    print(''.join(perm))

Using Libraries

In Python, we can use the built-in itertools module to generate permutations seamlessly:

python
1import itertools
2
3elements = 'ABC'
4perms = itertools.permutations(elements)
5
6for perm in perms:
7    print(''.join(perm))

Key Points Summary

FeatureDescription
DefinitionRearrangement of a set's elements to form new combinations.
Total PermutationsCalculated as n!n! (n factorial).
ApproachesRecursive, Iterative (e.g., Heap's), and Backtracking.
ComplexityTime: O(n!)O(n!), Space: O(n)O(n).
Python Library SupportUse itertools.permutations for easy implementation.

Conclusion

Understanding the permutations of a string or integer is crucial for numerous computational tasks. With both recursive and iterative methods at our disposal, and Python libraries simplifying the process, generating permutations becomes an accessible task for programmers. Whether for academic pursuits or solving complex real-world problems, mastery of permutations is an invaluable tool.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.