Hashing: Dictionaries and Sets
A hash table (Python's dict and set) finds a key in O(1) on average. It is the number-one tool for turning slow solutions into fast ones.
A hash table (Python dict or set) finds any item in about constant time, no matter how many items there are. This single idea solves a huge number of problems: duplicates, counts, "have I seen this before?", and the famous two-sum. When a brute-force solution checks every pair, a hash table is often the fix.
Two Sum - the most famous interview question
Find two numbers that add up to a target. Remember each number's index in a dictionary; for every new number, check whether its partner is already there.
Example
Group anagrams
Example
Counting frequencies
Example
Dictionary keys must be immutable: numbers, strings, tuples. A list can't be a key - use
tuple(my_list) instead.Key points
- dict and set look up items in O(1) on average.
- Use them for counting, duplicates and seen-before checks.
- They trade memory for speed.
📝 Test yourself
1. What is the average time to check 'x in my_set'?
2. In Two Sum, what do we store in the dictionary?
3. Fill in the dict method that returns a default when the key is missing:
counts[x] = counts.(x, 0) + 1
