Hashing with Maps and Sets
Use hash maps and sets to trade memory for speed: counting, seen-before checks, grouping and complement lookups.
Beginner · about 6 hours · difficulty 2/5
Learn first: Strings
Hashing is the single most useful trick in interviews. Whenever a brute force asks "have I seen something like this before?", a hash map or set usually removes a whole loop.
Key patterns
- Complement lookup: store values as you scan and check for target minus current (Two Sum in O(n)).
- Frequency count: Top K Frequent Elements, First Unique Character, Majority Element.
- Grouping by a canonical key: sorted string or count signature as the key (Group Anagrams).
- Seen set: Contains Duplicate, Longest Consecutive Sequence (start counting only from numbers whose predecessor is missing).
- Prefix sum + map: count subarrays with sum k (covered in the prefix sums topic).
How it works underneath
A hash function maps a key to a bucket. Collisions are handled by chaining or open addressing. Average O(1), worst case O(n). Ordered maps (C++ map, Java TreeMap) are balanced BSTs with O(log n) but keep keys sorted, which you need for floor and ceiling queries.
Pitfalls
- Using a hash map when a fixed-size array would do (characters, small value ranges).
- Mutable or custom keys: in C++ a pair needs a custom hash for unordered_map; in Java override equals and hashCode.
- Iterating a hash map and expecting sorted order.
You are ready to move on when you can solve Two Sum, Group Anagrams and Longest Consecutive Sequence in O(n) and explain the worst case of a hash map.
Key concepts
- Complement lookup
- Frequency counting
- Grouping by canonical key
- Seen sets and duplicates
- Collisions and worst case
- Hash map vs ordered map
- Custom keys and hash functions
Mini project
Solve these 10 in 7 days, log time and pattern: Two Sum, Contains Duplicate, Valid Anagram, Group Anagrams, Top K Frequent Elements, Longest Consecutive Sequence, First Unique Character in a String, Isomorphic Strings, Word Pattern, Encode and Decode Strings.
Check yourself
In Longest Consecutive Sequence, why does starting a count only when x - 1 is absent keep the whole algorithm O(n)?
Free resources
- NeetCode roadmap: Arrays and Hashing (NeetCode)
- cppreference: unordered_map (cppreference)
- takeUforward (takeUforward)