Command Palette

Search for a command to run...

← All patterns

Pattern · Hashing & Counting

Frequency Counting

Count how many times each value appears (with an int[26] or a HashMap), then answer from the counts.

Time O(n) · Space O(alphabet) or O(n)

Taught in Module 4: Hashing

Think of it like this

Counting votes with tally marks: you don't remember who voted first, just how many votes each name got.

Clues that point here

  • → Anagrams
  • → "Most frequent", "first unique", "majority element"
  • → Compare the content of two strings ignoring order
  • → Group items by their letters

Not this pattern when

  • ✕ Order or position matters (counts lose it)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Frequency Counting · template
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
for (char c : t.toCharArray()) count[c - 'a']--;
for (int n : count) if (n != 0) return false;   // some letter count differs
return true;

Common versions

  • Valid anagram
  • Group anagrams (sorted key or count key)
  • Top K frequent elements
  • First unique character
  • Majority element

Practice problems with this pattern

Related patterns