Hash Maps for Coding Interviews: A Crash Course
If you only master one data structure before an interview, make it the hash map. It turns slow searches into instant lookups, and it shows up in a huge share of array and string problems.
A hash map stores pairs of keys and values.
You give it a key, and it hands back the value stored for that key.
Python calls it a dict, Java a HashMap, and JavaScript a Map.
The idea and the costs are the same in every language.
1) Core Hash Map Operations
Almost everything you do with a hash map is one of these operations. Learn their costs, because the difference between O(1) and O(n) is usually what separates the brute force answer from the optimal one.
2) Three Ways Interviews Use Hash Maps
Most hash map problems are a variation of one of these three ideas.
3) What Happens Under the Hood
A hash map is really an array of buckets plus a function that turns any key into a bucket index.
NOTES
- Average case lookups, inserts and deletes are O(1). The worst case is O(n) when many keys collide, which almost never matters in interviews.
- Keys must be hashable. In Python that means immutable values such as numbers, strings and tuples, so use a tuple instead of a list as a key.
- A set is a hash map that only stores keys.
- Iteration order follows insertion order in modern Python, but do not rely on it in other languages.
- Reach for a hash map whenever a problem asks whether you have seen something before, or how many times something appears.