← Back to Patterns
Data StructuresEasy

Hash Map

O(1) average lookup by trading space for time — map values to indices or counts.

How it works

A Hash Map stores key-value pairs with O(1) average time for insert, delete, and lookup (O(n) worst case due to hash collisions, which are rare with a good hash function). In algorithm problems, hash maps are used to eliminate the need for nested loops: instead of checking all pairs, store what you've already seen. Common patterns: (1) Complement lookup — for Two Sum, store value→index and look up target-current. (2) Frequency counting — store character→count to find duplicates or anagrams. (3) Grouping — store key→list for grouping by sorted string, prefix, or property. (4) Memoization — store input→result for recursive functions.

Interactive Playground

[0][1][2][3][4][5]

Hash map with 6 buckets. Keys map to buckets via hash function.

Speed

When to use

  • Two Sum style complement lookup
  • Frequency counting and grouping
  • Detecting duplicates or finding first unique

Tips

1For Two Sum, build the map as you iterate — no need for a separate pass.
2Use `defaultdict(int)` or `Counter` in Python for frequency maps without explicit initialization.
3For anagram grouping, the key is `tuple(sorted(word))` or the sorted string itself.
4Hash Set (set of values, no associated data) is O(1) for contains check — prefer it over a list for membership.

Common Mistakes

!KeyError when accessing a key that doesn't exist — use `.get(key, default)` or `defaultdict`.
!Using a list for O(n) membership checks — use a set or hash map for O(1) lookups.
!Modifying the map while iterating over it — iterate over a copy or collect keys to delete first.
!Not accounting for case sensitivity or Unicode normalization in string key problems.
💡 Key Insight:Store what you've seen so far: value→index, char→count, or key→list.