Skip to main content

Command Palette

Search for a command to run...

unordered_map in C++

Published
β€’3 min readβ€’View as Markdown
R

πŸŽ“ B.Tech CSE | πŸ‘¨β€πŸ’» Learning DSA & C++ | πŸš€ Building projects & writing what I learn | πŸ“š Currently solving LeetCode & exploring Git/GitHub


πŸ”Ή What is unordered_map?

  • A key β†’ value container from C++ STL.

  • Similar to map, but does NOT store keys in sorted order.

  • Keys are stored in buckets using hashing.

  • Provides average O(1) lookup, insert, erase (faster than map).

  • Order of keys is unpredictable.

πŸ‘‰ Think of it as a hash table implementation of a dictionary.


πŸ”Ή Syntax

unordered_map<KeyType, ValueType> mp;

Example:

unordered_map<string, int> age;
age["Alice"] = 20;
age["Bob"] = 25;

Storage (order is not guaranteed):

"Bob"   β†’ 25
"Alice" β†’ 20

πŸ”Ή Common Operations & Complexity

OperationCode ExampleAvg TimeWorst Time
Insertmp[key] = value; or mp.insert({key,value});O(1)O(n)
Access (by key)mp[key]O(1)O(n)
Searchmp.find(key)O(1)O(n)
Erasemp.erase(key)O(1)O(n)
Sizemp.size()O(1)O(1)
Iteratefor (auto &p: mp) ...O(n)O(n)

⚠️ Worst-case O(n) happens if many keys land in the same bucket (hash collisions). But in practice, it’s rare.


πŸ”Ή Example

unordered_map<int, string> mp;
mp[30] = "X";
mp[10] = "Y";
mp[20] = "Z";

// Order is not guaranteed!
// Could print: 20β†’Z, 30β†’X, 10β†’Y

πŸ”Ή Checking Existence

if (mp.find(20) != mp.end()) {
    cout << "Key 20 found, value = " << mp[20];
}
else {
    cout << "Key 20 not found";
}

πŸ”Ή Iteration

for (auto &p : mp) {
    cout << p.first << " β†’ " << p.second << endl;
}

⚠️ Unlike map, iteration order is unpredictable (depends on hashing).


πŸ”Ή Characteristics

  1. Unordered β†’ No sorting of keys.

  2. Unique keys β†’ Each key is stored only once.

  3. Underlying data structure β†’ Hash Table.

  4. Fast average operations β†’ O(1).


πŸ”Ή Advantages (Pros)

βœ… Much faster than map for lookups (average O(1)).
βœ… Great for frequency counting, existence check, hash-based problems.
βœ… Easy syntax like map.


πŸ”Ή Disadvantages (Cons)

❌ Keys are not stored in order β†’ no range queries, no smallest/largest key.
❌ Slightly more memory usage due to hashing buckets.
❌ Worst-case O(n) time (though rare with good hash functions).
❌ Doesn’t work well with custom complex types unless you define a hash function.


πŸ”Ή map vs unordered_map

Featuremap (Red-Black Tree)unordered_map (Hash Table)
Order of keysSortedNo order
Lookup/Insert/EraseO(log n)O(1) average, O(n) worst
Use caseNeed ordering, rangesJust need fast lookups
MemoryLowerHigher (hash overhead)

πŸ”Ή Typical LeetCode Use Cases

  • Two Sum (store number β†’ index for O(n) solution).

  • Counting frequency of elements.

      unordered_map<int,int> freq;
      for (int x : nums) freq[x]++;
    
  • Checking existence in O(1).

  • Prefix sums / subarray problems.

  • Graph adjacency list (fast access).


βœ… Summary

  • unordered_map = Hash table based key-value store.

  • Operations = O(1) average.

  • Faster than map if you don’t care about sorting.

  • Use in LeetCode most of the time unless the problem needs sorted keys.


πŸ‘‰ So:

  • Use unordered_map by default for speed.

  • Use map if you specifically need sorted keys or range queries.