BeginnerArrays & Strings

Counting things with a hash map

, majority element, most frequent: they're all “count each value”. A from value to count does it in one pass.

The idea

A hash map (dict in Python) stores key → value pairs with lookups. Use the item as the key and how many times you've seen it as the value.

Two strings are anagrams exactly when every letter has the same count in both, so counting turns the problem into comparing two maps.

Worked example

Valid Anagram: “listen” vs “silent”

  1. Count “listen”: l:1 i:1 s:1 t:1 e:1 n:1
  2. Count “silent”: s:1 i:1 l:1 e:1 n:1 t:1
  3. Same keys with the same counts → anagram.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

counts ← empty map
for each item x:
counts[x] ← (counts[x], or 0 if missing) + 1
return counts

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

items = "banana"

0b
1a
2n
3a
4n
5a

seen

{ } empty — nothing seen yet

Solution · Pythonline 8

from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
# Without Counter:
def counts(s):
seen = {}
for ch in s:
seen[ch] = seen.get(ch, 0) + 1
return seen

Step 1 of 8· line 8

An empty map: letter → how many times we've seen it.

time, O(k) space for k distinct items.

How to spot it

  • “anagram”, “frequency”, “most common”, “appears more than n/2 times”.

Common mistakes

  • Forgetting the length check shortcut: different lengths can't be anagrams.
  • Sorting both strings works but is ; counting is O(n).

Practise the ideas first

Practise it

Go further