DEPLOYEDAI-era interview training
RankBootstrapping
XP 0 / 250
0
0%
Ready
Coding Interview: Patterns & DSA · Hashing & Sets · Lesson 1 of 2

Frequency maps & counting

6 min

A hash map gives O(1) average insert and lookup, which lets you trade memory for time — the single most common optimization in coding interviews. A frequency map counts how many times each value appears, unlocking anagrams, majority elements, and top-K.

def char_counts(s):
    counts = {}
    for c in s:
        counts[c] = counts.get(c, 0) + 1
    return counts

# two strings are anagrams iff their frequency maps are equal
def is_anagram(a, b):
    return char_counts(a) == char_counts(b)
  • Anagram grouping: use a canonical key (sorted string, or a 26-length count tuple) so anagrams collide into the same bucket.
  • Majority / mode: count occurrences, then take the max — or, when a strict majority (> n/2) element is guaranteed, Boyer-Moore voting for O(1) space (it finds the majority, not the mode).
  • Top-K frequent: build the frequency map, then bucket or heap by count.
The core tradeAlmost every 'can you do better than O(n^2)?' hint is really asking: can a hash map remember what you have already seen, so you never rescan? Space for time is the reflex answer.

◆ Lock it in

  • Hash maps give O(1) average lookup — trade space for time.
  • A frequency map powers anagrams, mode, and top-K problems.
  • Anagrams share a canonical key (sorted string or count tuple).
Feynman drill — say it out loudExplain why comparing two frequency maps decides anagrams in O(n) instead of O(n log n) sorting.
Step 1 rate your confidence · Step 2 pick your answer
The main reason a hash map speeds up 'have I seen this before?' checks is:
Step 1 — how sure are you?