A calculus of the absurd

16.3 Listing all permutations of a string

Sometimes, we have a string (e.g. "MATHS"), of which we’d like to list out all the possible permutations. To list these, we have to do this systematically. A nice way to do this is using Heap’s algorithm. To generate all the permutations of a string, we first pick one letter. When we generate all the permutations of this string, we will have different strings, each of which has that letter at a different position. For example, in the case of "MATHS", we will have all the following (where “_” means we don’t know what letter will be at that position.)

  • • “M____”

  • • “_M___”

  • • “__M__”

  • • “___M_”

  • • “____M”

The key idea of Heap’s algorithm is that in each of these cases, the valid choices for the four unknown items (“_”) are any of the permutations of the four letters in question. This means that we’ve found a way to write the permutations of five letters (which we don’t know) in terms of the permutations of four letters arranged with a known letter in-between them. From here, we can apply the same algorithm many times - for the four-letter permutation we can reduce it to a three letter permutation, and so on until we have only one letter left. In this case, there is only one possible permutation.

There are too many possibilities here to list out all the permutations, but for the first one (“M____”), the process would go something like this:

  • • “MA___”

  • • “M_A__”

  • • “M__A_”

  • • “M___A”

If we then pick the first one here (the process for the rest is the same) we have

  • • “MAT__”

  • • “MA_T_”

  • • “MA__T”

proceeding with the first one again

  • • “MATH_”

  • • “MAT_H”

and then finally

  • • “MATHS”

There are a lot more possibilities than that, but I’ve only listed out some of them; to obtain the full list, just continue the process.