Permutations
String Manipulation
Algorithm Design
Programming
Computer Science

Generating all permutations of a given string

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

Permutations of a string involve rearranging its characters in all possible orders. This concept is fundamental in fields like combinatorics, cryptography, and algorithm design. It's critical to understand how strings, or any set of items, can be permutated because these sequences are significant in solving various computational problems.

Understanding Permutations

A permutation is any reordering of elements from a set. If the set is the string "ABC", the permutations include "ABC", "ACB", "BAC", "BCA", "CAB", and "CBA". The count of possible permutations of a string of length nn is given by n!n! (n factorial), which means n×(n1)×...×1n \times (n-1) \times ... \times 1.

For instance, a string of length 3, like "ABC", would have 3!=63! = 6 permutations. As the length of the string increases, the number of permutations grows exponentially, making it computationally expensive to generate all permutations for large strings.

Methods of Generating Permutations

1. Recursion

A popular method to generate permutations is using recursion. This involves breaking down the problem into smaller sub-problems. Here’s a basic conceptual breakdown:

  • Take each character of the string and set it as the first character.
  • Permute the rest of the string recursively.
  • For a string "ABC", selecting 'A', the problem then reduces to permuting "BC".

Here's a simple Python code that demonstrates this method:

python
1def permute(data, i, length):
2    if i==length:
3        print(''.join(data) )
4    else:
5        for j in range(i, length):
6            # swap
7            data[i], data[j] = data[j], data[i]
8            permute(data, i+1, length)
9            # backtrack
10            data[i], data[j] = data[j], data[i]
11
12string = "ABC"
13n = len(string)
14data = list(string)
15permute(data, 0, n)

2. Backtracking

Backtracking is an improved recursive approach. It reduces the problem space by "backtracking" before going to the next possibility, rectifying potential miscalculations in previous arrangements.

3. Lexicographic Order (Non-Recursive)

Generating permutations in lexicographic order is another method. This approach doesn't require recursion and follows a specific sequence from the smallest lexicographical permutation to the largest. The algorithm involves:

  • Finding the rightmost character that is smaller than its next character.
  • Finding the ceiling of this character on its right.
  • Swapping them and reversing the order of characters to the right of the original position.

Applications of String Permutations

Permutations are utilized in various practical applications:

  • Algorithm design: For testing and developing algorithms under all possible cases.
  • Cryptography: For generating different combinations of passwords or keys.
  • Game development: To generate all possible outcomes or moves.

Summary Table

MethodComputational ComplexityRecursion UsedUse Case
RecursionHigh (O(n!))YesSmall strings, educational purpose
BacktrackingModerate-High (O(n!))YesEfficient for medium-length strings
Lexicographic OrderModerate (O(n!))NoGenerating ordered permutations

Conclusion

Understanding how to generate all permutations of a string allows developers and algorithm designers to better tackle problems involving different combinations and arrangements. Between recursive, backtracking, and lexicographic methods, the choice depends on specific requirements such as the need for ordered permutations or computational resources available. Each method provides its toolkit for effectively handling the complexity and size of the problem at hand.


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.