Hash Tables and Hashing Patterns

Learn how hash maps and sets work internally and apply them to frequency counting, complement lookups, grouping and de-duplication.

Beginner · about 6 hours · difficulty 2/5

Learn first: Array and String Fundamentals

A hash table maps keys to values with O(1) average insert, delete and lookup. It is the single most useful tool for turning brute-force O(n^2) searches into O(n).

How it works

A hash function converts a key to an integer, which is reduced to a bucket index. Different keys can land in the same bucket (collisions). Two common resolutions:

  • Chaining: each bucket holds a list of entries (Java HashMap, C++ unordered_map).
  • Open addressing: probe for the next free slot (Python dict).

When the load factor grows, the table resizes and rehashes, which is O(n) but rare, so operations stay O(1) amortized. The worst case is O(n) if many keys collide; this is why contest solutions sometimes get hacked with anti-hash tests and use custom hashes.

Patterns

  • Frequency counting: anagrams, majority element, first unique character.
  • Complement lookup: Two Sum stores seen values and checks target - x.
  • Grouping by a canonical key: sorted string or character counts for Group Anagrams.
  • Seen set: detect duplicates, cycles or longest consecutive sequence.
  • Prefix sum + hashmap: count subarrays with a given sum (see the prefix sums topic).

Ordered vs unordered

Use a hash map when you only need lookups. Use an ordered map (TreeMap, std::map) when you need sorted iteration or "nearest key" queries, at O(log n) per operation.

Pitfall: mutable objects as keys, and assuming iteration order in a hash map.

Key concepts

  • Hash functions and buckets
  • Chaining vs open addressing
  • Load factor and rehashing
  • Frequency counting
  • Complement lookup (Two Sum)
  • Grouping by canonical key
  • Ordered vs unordered maps
  • Anti-hash tests and custom hashes

Mini project

Implement a tiny hash map with chaining and resizing, then solve 8 problems: Two Sum, Valid Anagram, Group Anagrams, Top K Frequent Elements, Longest Consecutive Sequence, Contains Duplicate II, First Unique Character, and Isomorphic Strings.

Check yourself

Why is hash map lookup O(1) on average but O(n) in the worst case, and when would you prefer a TreeMap instead?

Free resources