M06 · Strings

Counting Characters: Frequency Tables, Anagrams and Palindromes

Many string questions reduce to "how often does each character occur?". This lesson compares a fixed-size counting array with a hash map, solves anagram and palindrome checks in linear time, and points to the problem bank, where each one runs step by step in its own visualizer.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M06 Strings · 3 of 3 lessons available

You will be able to

  • Build a character frequency table with a fixed array or a hash map, and say when each is the better choice.
  • Decide whether two strings are anagrams in O(n) time with one table.
  • Check a palindrome with two pointers while skipping characters that do not count.
  • State the space cost of a frequency table in terms of the alphabet size, not the input size.

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Why this lesson has no visualizer of its own

Every technique here is already animated, step by step and in four languages, by a problem in the problem bank: the anagram check, the palindrome check, run-length encoding and the longest substring without repeats. Building a second, near-identical lab would only duplicate them, so this lesson explains the shared idea and links to those problems instead.

Mental model

A frequency table maps each character to how many times it occurs. Once you have it, questions about the multiset of characters become cheap: are two words anagrams, can the letters of a ransom note be cut from a magazine, which character appears most, is there a character that occurs only once.

The table has one slot per possible character, not per input position. Its size depends on the alphabet, which is why it is often called O(1) extra space for a fixed alphabet and O(k) in general, where k is the number of distinct characters.

Two ways to store the counts

Fixed array Hash map
Index c - 'a' (26 slots) or the byte value (256 slots) the character itself
Works for a small, known alphabet any alphabet, including all of Unicode
Cost per update O(1), no hashing O(1) expected, with hashing
Memory fixed (26 or 256 counters) proportional to the distinct characters seen

For "lowercase English letters", the array is simpler and faster. For arbitrary text, a map keyed by code point (or by grapheme cluster, if the question is about what a reader sees) is the honest choice. A 26-slot array silently breaks on "é" or uppercase input; validate or normalise first.

counts = array of 26 zeros
for c in text:
    counts[c - 'a'] += 1

Anagrams in one pass

Two strings are anagrams when they contain the same characters with the same counts. Sorting both and comparing works in O(n log n). Counting does it in O(n): add one for every character of the first string, subtract one for every character of the second, and check that every count is zero.

if len(a) != len(b): return false
counts = empty table
for c in a: counts[c] += 1
for c in b:
    counts[c] -= 1
    if counts[c] < 0: return false     # b has more of c than a
return true                            # equal lengths, no negative count: all zero

The early exit is safe: with equal lengths, a negative count somewhere means a positive count somewhere else. Run it in Same letters, different order?, which shows the table filling and draining.

Palindromes with two pointers

A palindrome needs no table at all: compare the first and last characters and move inward. To ignore punctuation and case, skip characters that do not count before each comparison. That is the opposite-ends pattern from the two-pointer lesson, O(n) time and O(1) space. Try it in Does the phrase read the same both ways?.

A related counting fact: the letters of a word can be rearranged into a palindrome exactly when at most one character has an odd count. That one needs a table, not two pointers.

Other counting patterns in the problem bank

Complexity

Task Time Extra space
Frequency table O(n) O(k), k = alphabet or distinct characters
Anagram by sorting O(n log n) O(n) for the sorted copies (strings are immutable)
Anagram by counting O(n) O(k)
Palindrome with two pointers O(n) O(1)

Language notes

C#. int[] counts = new int[26]; counts[c - 'a']++; works because char converts to int. For general text use Dictionary<char, int> with CollectionsMarshal.GetValueRefOrAddDefault, or LINQ GroupBy (shorter, slower). Remember that char is a UTF-16 unit, so an emoji is counted as two surrogates; key by Rune (from EnumerateRunes()) to count code points.

Python. collections.Counter(text) builds the table in one call, and Counter(a) == Counter(b) is an anagram test. A str iterates code points, so "é" written as e + U+0301 counts as two entries. [0] * 26 with ord(c) - ord('a') is the array version.

Java. int[] counts = new int[26]; counts[c - 'a']++; for letters. For maps, counts.merge(c, 1, Integer::sum) avoids a separate get and put. Boxing Character and Integer costs memory, so prefer the array when the alphabet allows. Iterate text.codePoints() for code points.

C++. std::array<int, 26> counts{} value-initialises to zero. Index with static_cast<unsigned char>(c) when using 256 slots: plain char may be signed, and a negative index is undefined behaviour. A std::string holding UTF-8 gives you bytes, so "é" contributes two counts unless you decode it first. std::unordered_map<char32_t, int> handles decoded code points.

Common mistakes

  • Assuming lowercase ASCII and indexing c - 'a' with "A", a space or "é": the index is out of range (an exception in C#, Java and Python lists, undefined behaviour in C++).
  • Forgetting the length check in the one-table anagram test.
  • Sorting to compare when counting would do, especially in a loop over many words.
  • Counting code units instead of characters in C#, Java or C++ for non-ASCII text.

Worked practice

1. Are "listen" and "silent" anagrams? Trace the counts.

Answer

After the first word: l, i, s, t, e, n each 1. Subtracting "silent" brings every count back to 0 and none goes negative: yes.

2. Can "carerac" be rearranged into a palindrome?

Answer

Counts: c 2, a 2, r 2, e 1. Only one odd count (e), so yes: "racecar".

3. Why is a 26-entry counting array O(1) space even for a million-character input?

Answer

Its size depends on the alphabet, not on n. For an unbounded alphabet the honest bound is O(k) for k distinct characters, which is at most min(n, alphabet size).

Summary

  • A frequency table turns multiset questions into O(n) passes; its size depends on the alphabet.
  • Use a fixed array for a small known alphabet, a hash map otherwise.
  • Anagram: one table, add then subtract, with a length check.
  • Palindrome: two pointers, no table; rearrangeable into a palindrome: at most one odd count.

References