Lesson 7 of 12

Hashing and exact-key queries

Understand unordered maps, deterministic output, and average versus worst-case cost.

Same records, different guarantees

std::unordered_map, from <unordered_map>, also associates one value with each unique key. Hashing selects buckets and equality checks distinguish keys within them. Different keys can collide without overwriting each other.

Traversal is neither promised to be sorted nor to follow insertion order. begin() does not mean minimum. There are no ordered lower_bound, upper_bound, or rank-selection member operations. Exact-key lookup, insertion, and key erasure are average O(1) for fixed-size keys but can be O(d) in the worst case.

Keep missing queries read-only

The subscript insertion rule still applies. Query with find and return zero on absence if the problem asks for a missing key’s frequency; this preserves the number of distinct input keys.

For sorted output, either use std::map or copy hash entries into a vector and sort it. That extra sort costs O(d log(d + 1)); a hash build followed by sorted output is not simply O(n). Include copied records, buckets, and key text in storage estimates.

C++23
// Complete C++23 program. Input: n q, n keys, q query keys.
#include <iostream>
#include <unordered_map>
int main() {
    int n, q;
    std::cin >> n >> q;
    std::unordered_map<int, int> frequency;
    for (int i = 0; i < n; ++i) {
        int x;
        std::cin >> x;
        ++frequency[x];
    }
    while (q--) {
        int x;
        std::cin >> x;
        auto it = frequency.find(x);
        std::cout << (it == frequency.end() ? 0 : it->second)
                  << '\n';
    }
    std::cout << frequency.size() << '\n';
}

Optional tuning: reserve and rehash

reserve(n) plans bucket room for roughly n entries under the current maximum load factor; it inserts no records. rehash(b) requests a bucket-count lower bound subject to load requirements, not an exact bucket count. Set a chosen max_load_factor before reserve, and avoid repeatedly reserving in a tight loop.

Rehashing invalidates iterators and can change traversal order, but references and pointers to surviving elements remain valid. Insertion can trigger rehashing, so reacquire iterators after operations that may rehash. Erasing an element still invalidates references to that element. Reserving does not remove collisions or promise worst-case constant lookup.

Word frequency map

Split on whitespace. Keys are case-sensitive; punctuation stays attached. Displayed in sorted key order like std::map<string, int>.

code3
learn2
solve1

6 words · 3 distinct keys

Guided simulation · Change the inputs to test your understanding.

Pause & predict

An empty unordered_map reserves room for 1000 entries. Which statement is guaranteed?

Choose an answer
Try it yourself

Turn the idea into code

A frequency hash map contains 8 → 2, 2 → 2, 3 → 1. Query absent key 99 without changing the final distinct count. How would you print all records in sorted order?

Give me a hint

Separate exact-key lookup from output ordering.

Show the explained solution

Use find(99); its end() result means output zero, and size() stays 3. For deterministic numeric order, copy entries into a vector of pairs and sort it, or build an ordered map originally. A direct hash traversal does not guarantee 2, 3, 8.

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.