Difficulty: Intermediate
Compare std::map and std::unordered_map (and set vs unordered_set). What are their complexities, and how do you choose among vector, list, deque, map and unordered_map?
Picking the right container is a core skill, and this question tests whether you know not just Big-O but also what the containers are made of. Let's compare the two associative families first.
std::map (and std::set) is an ordered associative container, implemented as a self-balancing binary search tree, usually a red-black tree. Keys are kept sorted, so iteration gives you keys in ascending order. Insert, erase, and find are O(log n) guaranteed. It needs an ordering, by default operator<, or a custom comparator. std::unordered_map (and unordered_set) is a hash table: keys are hashed into buckets, so insert, find, and erase are O(1) on average, but degrade to O(n) in the worst case when many keys collide. Iteration order is unspecified. It needs a hash function and operator== for the key type, which is why using a pair or a custom struct as a key requires you to supply a hash. Think of map as a dictionary printed in alphabetical order, and unordered_map as a set of lockers where the key's hash tells you which locker to open.
How do you choose? Use unordered_map when you just need fast lookups and don't care about order, as in frequency counting or memoisation. Use map when you need sorted iteration, range queries (lower_bound, upper_bound), the smallest or largest key, or predictable worst-case performance. In adversarial settings, hash tables can be attacked with collisions. Also note that unordered_map has larger constant factors in memory (buckets and node allocations), and rehashing invalidates iterators, while map iterators stay valid across inserts.
A well-known gotcha is operator[]: on a map or unordered_map, m[key] inserts a default-constructed value if the key is absent. So using it in a read-only check silently grows your container. Use find() or count() (or contains() in C++20) to test presence, and at() to throw for a missing key. Use try_emplace or insert_or_assign for precise insertion semantics. Also, multimap and multiset allow duplicate keys.
For the sequence containers: vector is the default, with contiguous memory, O(1) random access, amortised O(1) push_back, and excellent cache behaviour. deque offers O(1) push and pop at both ends and O(1) random access, but with non-contiguous chunks, and is the backing store for std::queue and std::stack. list is a doubly linked list with O(1) insertion and erase anywhere given an iterator, but O(n) to find a position, no random access, and poor cache locality, so it rarely wins in practice. forward_list is the singly linked version. Bjarne Stroustrup's advice is famous: use vector unless you have a measured reason not to.
In interviews, mention the underlying structure, the complexities, and one gotcha (operator[] insertion, or iterator invalidation). That trio is what earns the full mark.
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
std::vector<std::string> words{"pear", "apple", "pear", "fig", "apple", "pear"};
std::map<std::string, int> ordered; // sorted by key
std::unordered_map<std::string, int> hashed; // no order guarantee
for (const auto& w : words) { ++ordered[w]; ++hashed[w]; }
for (const auto& [word, n] : ordered) std::cout << word << "=" << n << " ";
std::cout << "\n";
std::cout << hashed.at("pear") << "\n";
std::cout << hashed.count("kiwi") << " " << hashed.size() << "\n";
int x = hashed["kiwi"]; // operator[] INSERTS a default 0 value
std::cout << x << " " << hashed.size() << "\n";
}
Iterating the map yields sorted keys. Calling count() does not insert, but operator[] on a missing key does, growing the map from 3 to 4 entries.
std::map, std::unordered_map, std::set, complexity, container selection