Arrays & Hashing · Pattern 14 of 26
Hashing: count, group and map
A hash map turns "search the whole array" into one lookup. Count frequencies, group items by a canonical key, or map one thing to another to check a one-to-one rule.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Anagrams, frequencies, "first unique", "most common"
- Group items that are the same under some transformation
- Two strings must follow the same pattern
- Check many candidates quickly against a set
The template
boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26]; // a fixed alphabet: an array is a hash map
for (int i = 0; i < s.length(); i++) { count[s.charAt(i) - 'a']++; count[t.charAt(i) - 'a']--; }
for (int c : count) if (c != 0) return false;
return true;
}
int firstUniqChar(String s) {
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
for (int i = 0; i < s.length(); i++) if (freq.get(s.charAt(i)) == 1) return i;
return -1;
} from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
def first_uniq_char(s):
freq = Counter(s)
for i, c in enumerate(s):
if freq[c] == 1:
return i
return -1
# grouping by a canonical key: groups[''.join(sorted(word))].append(word) bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {0}; // a fixed alphabet: an array is a hash map
for (size_t i = 0; i < s.size(); i++) { count[s[i] - 'a']++; count[t[i] - 'a']--; }
for (int c : count) if (c != 0) return false;
return true;
}
int firstUniqChar(string s) {
unordered_map<char, int> freq;
for (char c : s) freq[c]++;
for (int i = 0; i < (int)s.size(); i++) if (freq[s[i]] == 1) return i;
return -1;
} function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = new Map();
for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
for (const c of t) {
if (!count.get(c)) return false;
count.set(c, count.get(c) - 1);
}
return true;
}
function firstUniqChar(s) {
const freq = new Map();
for (const c of s) freq.set(c, (freq.get(c) ?? 0) + 1);
for (let i = 0; i < s.length; i++) if (freq.get(s[i]) === 1) return i;
return -1;
} The variations
-
1Count frequencies
One pass to count, one pass to answer. A 26-slot array is the fastest map for lowercase letters.
Now you solve- First Unique Character in a String Easy Stuck? solution
- Count Elements With Maximum Frequency Easy Stuck? solution
- Find The Least Frequent Digit Easy Stuck? solution
- Minimum Number of Steps to Make Two Strings Anagram Medium Stuck? solution
- Degree of an Array Easy Stuck? ▶ video
- Custom Sort String Medium Stuck? ▶ video
- Subdomain Visit Count Medium Stuck? ▶ video
-
2Group by a canonical key
Map every item to a key that is equal for items that belong together: sorted letters, shift distances, a reduced slope, a block corner.
Now you solve -
3Map one thing to another
Keep a map (sometimes two, one per direction) and check every new pair against it. Remainders that repeat mark a repeating decimal.
Now you solve- Valid Sudoku Medium Stuck? solution
- Task Scheduler II Medium Stuck? solution
- Fraction to Recurring Decimal Medium Stuck? solution
-
4Hash every variant
Put every candidate (each word with one letter masked, each reversed word, each substring) in a set or map, then look up instead of comparing pairs.
Now you solve -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Mistakes to avoid
- Using a list or array as a map key (Java arrays and Python lists hash by identity or fail). Use a string or tuple key.
- Sorting each word to build a key when a 26-letter count key is cheaper for long words.
- For one-to-one mapping, checking only one direction ("ab" → "aa" passes a one-way check).
Lesson done
Next: Matrix traversal: spirals and diagonals →Mark it done once you can write the template from memory and you have solved the worked examples yourself.