A hash map converts a key to a bucket index via: index = hash(key) % table_size. If two keys map to the same bucket (collision), they're stored in a linked list there (chaining). Average case: O(1). Worst case (all collide): O(n).
unordered_map = O(1) average. map = O(log n) ordered. Prefer unordered_map for speed unless you need sorted keys.unordered_map
Key → Value. O(1) avg. Use for lookup, grouping, memoization.
unordered_map<int,int> mp;
unordered_set
Keys only. O(1) membership check. Use for deduplication.
unordered_set<int> s;
map / set
Ordered (BST-backed). O(log n). Use when sorted order matters.
map<int,int> mp;
Frequency Count
Count occurrences of each element.
mp[x]++;Complement Lookup
Check if (target-x) was seen.
mp.count(target-x)Memoization
Cache recursive results.
memo[state]=resultGrouping
Group by a computed key.
mp[key].push_back(v)Index Tracking
Remember where you saw something.
seen[val]=indexDeduplication
Fast membership check.
s.count(x) → foundFrequency Map
Grouping by Computed Key (Group Anagrams)
8 buckets, h(k)=k mod 8. Watch how keys map to buckets and collisions form chains.
🧠 Under the Hood
Under the hood, unordered_map maintains an array of "bucket" lists. The hash function maps your key to a bucket index in O(1). If two keys share a bucket (collision), they are chained in a linked list inside that bucket. As the load factor (n/capacity) grows past ~0.75, the table automatically doubles its capacity and reinserts all keys — this rehash is O(n) but happens rarely.