Foundation 03
Hash Map
A table that associates each unique key with one value.
Mental model
What the structure guarantees
A hash function turns a key into a table position. Different keys can land in the same region, so the implementation also stores enough information to resolve collisions and still compare the original keys.
Implementation
How that model appears in code
Average constant-time lookup depends on a suitable hash function and enough table capacity. A hash map does not sort keys unless a different ordered-map implementation is chosen.
Hash Map basics
Map<String, Integer> count = new HashMap<>();
count.put("a", count.getOrDefault("a", 0) + 1);
boolean seen = count.containsKey("a");count = {}
count["a"] = count.get("a", 0) + 1
seen = "a" in countunordered_map<string, int> count;
count["a"] += 1;
bool seen = count.contains("a");Operation costs
What gets more expensive as the input grows
O(1) averageHashing selects a small table region.O(1) averageThe same hash leads back to its region.O(n)Every stored key-value pair is visited.O(n)Many collisions can force a long search.Tradeoffs
Choose it for the operations it makes cheap
Good fit
- Frequency counts
- Remembering an item’s earlier position
- Membership plus associated data
Poor fit
- Sorted traversal
- Range queries
- Small fixed key sets where an array is simpler
Used by
Common mistakes
Errors that survive a first glance
Missing is different from present with a zero value
Check key membership when that distinction changes the answer.
Mutable keys are unsafe
Changing a key after insertion can change its hash and make the entry unreachable.
Iteration order is not a sorting guarantee
Use an ordered map or sort the keys when order is part of the result.