Algorithmsstring permutations

String Permutations (orderings, small n)

TT
Testlaa Team
May 14, 20261 min read

Permutations reorder all characters—itertools.permutations yields tuples; join for strings. Factorial growth means only small n is feasible for full enumeration; larger problems need ranking or next-permutation tricks.

Why this shows up in the real world

Anagram games list every shuffle of a rack. Test generators brute small alphabets for property-based checks.

Core idea (explained for students)

Unique multiset perms: sort input, use set(permutations(...)) only when n is tiny—still expensive. For duplicates, Counter + combinatorics beats naive dedupe.

Try this in Python

from itertools import permutations


def all_perms(s: str) -> list[str]:
    return sorted({"".join(p) for p in permutations(s)})


print(all_perms("ab"))

Common mistakes

  • Treating permutations as strings without join—you get tuples.
  • Forgetting lex order requirements—sort before generating if output must be sorted.

Key takeaways

  • Estimate n! before running exhaustive permutations.
  • Learn next_permutation style for iterative interview patterns.

Tags:

StringsPythonStudents