Skip to main content

Maps as Thinking Tools

intermediate13 min readLesson 112 of 180

Counting, indexing, and grouping patterns that trade space for O(1) answers.

Maps as thinking tools

Many "hard" problems collapse once you choose the right auxiliary map:

  • counting โ€” freq.merge(x, 1, Integer::sum) turns "how many" into O(1) lookups (anagram detection, majority element)
  • indexing โ€” Map<Value, Index> remembers where you saw something (two-sum in one pass; last-seen index for window problems)
  • grouping โ€” groupingBy turns equivalence classes into buckets (group anagrams by their sorted-letter signature)
// two-sum, one pass โ€” O(n)
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < xs.length; i++) {
    Integer j = seen.get(target - xs[i]);
    if (j != null) return new int[]{j, i};
    seen.put(xs[i], i);
}

The pattern to internalize: trade space for a cheaper question. If a loop exists only to answer "have I seen X?", the map already knows.

Now practice

Algorithms LabTwo-pointer pairing, window shrinking, prefix-map subarray counting โ€” patterns over memorized answers.3 challenges ยท ยท ~40 min