← All patternsFrequency Counting · template
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.
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
4.2Valid AnagramEasymain pattern4.3First Unique CharacterEasymain pattern4.4Group AnagramsMediummain pattern4.5Top K Frequent ElementsMediummain pattern14.5Relative Sort ArrayEasymain pattern2.2Majority ElementEasyalso uses it7.4Longest Repeating Character ReplacementMediumalso uses it7.5Permutation in StringMediumalso uses it7.6Minimum Window SubstringHardalso uses it20.2Find the Town JudgeEasyalso uses it25.5Smallest String With SwapsMediumalso uses it28.5Delete and EarnMediumalso uses it33.10Hand of StraightsMediumalso uses it