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.

5 variations · 25 problems · 7 with animated walkthroughs

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

Hashing
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;
}

The variations

  1. 1Count frequencies

    One pass to count, one pass to answer. A 26-slot array is the fastest map for lowercase letters.

  2. 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.

    Worked example Group Anagrams Medium Read the solution
  3. 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.

  4. 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.

  5. 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).
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.