Algorithms Playbook
PatternTime O(n) · Space O(k)7 min read

Counting frequencies: anagrams, duplicates and the most common item

Count how many times each value appears, in one pass. The pattern behind anagrams, "first unique character", "top K frequent" and many sliding window problems.

In short

Walk the input once and keep a count per value in a hash map (or an array of 26 for letters). Comparing or querying counts replaces sorting and nested loops: O(n) time, O(k) space for k distinct values.

The idea: tally marks

Two words are anagrams if they use the same letters the same number of times. Sorting both works (O(n log n)), but counting is simpler: add one for each letter of the first word, subtract one for each letter of the second. If everything ends at zero, they match.

Counting frequencies: are two words anagrams?
Example
Speed
0l1i2s3t4e5ns = "listen"

t

0s1i2l3e4n5t

count (char → times)

{ }
1def is_anagram(s, t):
2 if len(s) != len(t):
3 return False
4 count = {}
5 for ch in s:
6 count[ch] = count.get(ch, 0) + 1
7 for ch in t:
8 count[ch] = count.get(ch, 0) - 1
9 if count[ch] < 0:
10 return False
11 return True
Different lengths can't be anagrams. Same length here, so count characters.

Variables

slisten
tsilent
Step 1/14· Characters counted: 0
Counting with a hash map (or an array of 26 for lowercase letters) is the go-to tool for anagrams, "most frequent" and "first unique" problems.

Array of 26 or hash map?

Array of 26 (or 128)

  • Only lowercase letters (or ASCII)
  • Fastest in practice, O(1) extra space
  • count[ord(c) - ord('a')] += 1

Hash map

  • Any keys: Unicode, numbers, words
  • O(k) space for k distinct keys
  • Counter(s) in Python, Map in TS, HashMap in Java

Problems that are secretly counting

ProblemWhat you count
Valid anagramLetters of s minus letters of t: all zero?
First unique characterCount all, then the first with count 1
Group anagramsUse the count (or sorted word) as the map key
Top K frequent elementsCount, then a heap or bucket sort by count
Ransom noteLetters available in the magazine vs needed

Key takeaways

  • 01Count each value once in O(n); compare or query counts instead of sorting.
  • 02Lowercase letters: an array of 26. Anything else: a hash map.
  • 03Anagrams, first unique, group anagrams and top K are all counting.
  • 04Counts inside a window are the engine of many sliding window problems.

Check your understanding

1 of 3

How do you check if two strings are anagrams in O(n)?

Related topics