Algorithmsstring canonical form

String Canonical Form (anagram keys, normalization)

TT
Testlaa Team
May 14, 20261 min read

Canonical forms normalize strings so logically equal values collide—sorted letters for anagram keys, lowercase + collapsed spaces for usernames, NFC Unicode normalization for filenames.

Why this shows up in the real world

Duplicate detection in uploads hashes canonical paths. Search indexes store stemmed or folded tokens.

Core idea (explained for students)

Anagram signature: ''.join(sorted(s)) (careful with space policy). For multiset with counts, tuple of sorted Counter.items() is tighter.

Try this in Python

def anagram_key(s: str) -> str:
    return "".join(sorted(s.replace(" ", "").lower()))


print(anagram_key("Listen") == anagram_key("Silent"))

Common mistakes

  • Sorting Unicode graphemes vs code points—requirements differ.
  • Locale-sensitive canonicalization needs casefold() not only lower().

Key takeaways

  • Document which equivalences you preserve (spaces, punctuation, case).
  • Prefer casefold for case-insensitive dictionary keys in Python 3.

Tags:

StringsPythonStudents