Skip to the page

Templates and the STL · core

map, unordered_map and set

map and set keep their keys sorted in a balanced tree, with O(log n) operations. unordered_map uses a hash table: O(1) on average, but with no order. Choose by whether you need the order.

The notes

What you must know

  • map<K, V> keeps unique keys in sorted order, usually as a red-black tree. Insert, find and erase are O(log n). Looping over a map gives the keys in increasing order.
  • unordered_map<K, V> puts keys into buckets by their hash, in no useful order. Insert, find and erase are O(1) on average and O(n) in the worst case, when many keys land in one bucket.
  • m[key] inserts the key with a default value (0 for int) when it is missing. To only check, use m.count(key), m.find(key) != m.end(), or m.contains(key) (C++20).
  • set<T> keeps unique values sorted, with O(log n) operations; multiset allows duplicates; unordered_set is the hash version.
  • s.lower_bound(x) gives the first element not less than x, in O(log n). std::lower_bound(s.begin(), s.end(), x) on a set moves one step at a time, so use the member function.
  • Count the pairs with sum k in O(n): for each x, add cnt[k - x] to the answer, then do cnt[x]++. This replaces the O(n^2) double loop.
  • Choose map when you need sorted keys, the smallest or largest key, or lower_bound. Choose unordered_map for plain lookups when speed matters.
  • A rehash in unordered_map makes its iterators invalid, but not references to elements. Some contest tests are built so that many keys collide; map, always O(log n), is the safe choice then.

The red pen

Common traps: mistake → fix

  • Mistake: if (m[key]) only checks the key

    Fix: it inserts the key when it is missing.

  • Mistake: unordered_map is always O(1)

    Fix: it is O(1) on average and O(n) in the worst case.

  • Mistake: map is a hash table

    Fix: it is a sorted tree; unordered_map is the hash table.

  • Mistake: set keeps duplicates

    Fix: use multiset for duplicates.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between map and unordered_map? When do you use each?
  2. What happens when you read m[key] for a key that is not in the map?
  3. Count the pairs whose sum is k in O(n).
  4. How do you find the smallest element that is greater than or equal to x in a set?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview