Algorithmschar frequency

Character Frequency in Strings

TT
Testlaa Team
May 14, 20261 min read

Character frequency counts how often each symbol appears. It unlocks anagram checks, rearrangement problems, and Huffman-style intuition long before compression math.

Why this shows up in the real world

Spell-checkers rank suggestions by how far letter counts differ from the typed word. Inventory SKU scanners tally item codes in batches. Poll workers count ballot marks per candidate—frequency tables everywhere.

Core idea (explained for students)

Python collections.Counter is ideal: Counter(s) then update in loops. For fixed lowercase English, a length-26 list using ord(ch)-ord('a') is faster and memory-light.

Try this in Python

from collections import Counter


def are_anagrams(a: str, b: str) -> bool:
    return Counter(a) == Counter(b)


print(are_anagrams("listen", "silent"))

Common mistakes

  • Counting bytes vs Unicode code points—emoji and combining marks can surprise length-based logic.
  • Mutating a shared Counter without copying when multiple windows need isolation.

Key takeaways

  • Frequency + sorting keys solves many permutation style problems.
  • Snapshot counts with tuple(counter.items()) when hashing states.

Tags:

StringsPythonStudents