Kodewick
Start learning →
Patterns: hash tables21 / 52

Patterns: hash tables

Lesson 21 of 52 · Part 4 · Hash tables · about 18 minutes

This review of hash tables covers three interview patterns, each a loop plus an unordered_map: two sum looks up the other half while walking, counting is cnt[x]++, and grouping uses a key that is the same within a group.

Interview hash table questions rarely ask you to write a table yourself; they ask how to use one. Many O(n²) problems become O(n) once an unordered_map remembers "what I've seen". The last three lessons showed what is inside the table; this one covers the three patterns you'll use most: look up while walking, counting, and grouping by a key. Each one is a loop plus a table.

Pattern 1: two sum, look up while walking

Given an array and a target, find two numbers that add up to target and return their indexes. Brute force is two nested loops, O(n²). Ask a different question instead: at x, ask "has target − x appeared before?" If so, you're done; if not, record x in the hash table. One pass, and each lookup and insert is O(1).

x % 50nullptr1nullptr2nullptr3nullptr4nullptr

Two sum - nums = 6 1 9 4 8, target = 13. The table stores "value [index]", drawn as 5 buckets with h(x) = x % 5

Look up first, then insert, never the other way round: insert x first and when target = 2x it pairs with itself. Run both versions side by side:

main.cpp
1#include <iostream>2#include <vector>3#include <unordered_map>4using namespace std;5 6int main() {7    const int N = 300;8    vector<int> a(N);9    for (int i = 0; i < N; i++) a[i] = 3 * i + 1;10    int target = a[N - 2] + a[N - 1];       // the answer is the last two: the worst case11 12    long brute = 0;13    int bi = -1, bj = -1;14    for (int i = 0; i < N && bi < 0; i++)15        for (int j = i + 1; j < N; j++) {16            brute++;17            if (a[i] + a[j] == target) { bi = i; bj = j; break; }18        }19    cout << "two loops:  " << bi << " " << bj << ", " << brute << " comparisons\n";20 21    unordered_map<int, int> seen;           // value → index22    long looks = 0;23    int hi = -1, hj = -1;24    for (int j = 0; j < N; j++) {25        looks++;26        auto it = seen.find(target - a[j]);  // look up first27        if (it != seen.end()) { hi = it->second; hj = j; break; }28        seen[a[j]] = j;                      // then insert29    }30    cout << "hash table: " << hi << " " << hj << ", " << looks << " lookups\n";31    return 0;32}
Output
two loops:  298 299, 44850 comparisons
hash table: 298 299, 300 lookups

With 300 numbers the two loops make 44850 comparisons and the hash table makes only 300 lookups, each O(1) on average; at n = 100,000 it's 5 billion against 100,000. The price is O(n) extra space: trading space for time, the most common use of a hash table. The lookup uses find, not seen[x]: [] would put a 0 in for a missing key, and index 0 would then look the same as "not there".

Choose one

nums = 3 5, target = 6. If the order is swapped, so the loop first does seen[a[j]] = j and then looks up target - a[j], which two indices does the program report? (-1 -1 if none.)

Exercise 1

Two sum

Fill in two_sum - for each j, first look for target - a[j] in seen and, if it's there, return {its index, j}; if not, record seen[a[j]] = j.

It should print
4 5
0 1
exercise1.cpp
1#include <iostream>2#include <vector>3#include <unordered_map>4using namespace std;5 6vector<int> two_sum(const vector<int>& a, int target) {7    unordered_map<int, int> seen;            // value → index8    for (int j = 0; j < (int)a.size(); j++) {9        // look up first: auto it = seen.find(target - a[j]); if found, return {it->second, j};10        // then insert: seen[a[j]] = j;11    }12    return {-1, -1};13}14 15int main() {16    vector<int> r = two_sum({11, 7, 2, 15, 8, 4}, 12);17    cout << r[0] << " " << r[1] << "\n";18    r = two_sum({3, 3}, 6);19    cout << r[0] << " " << r[1] << "\n";20    return 0;21}
Output
Press Run or Ctrl+Enter

Pattern 2: counting with unordered_map

"How many times does each thing appear" is always one table: the thing is the key, the count is the value. In an unordered_map<K, int>, cnt[x] first puts in a 0 for a missing key, so cnt[x]++ is all it takes, with no check whether it's there.

To find the first character that appears only once in a string: count in one pass, then in a second pass find, in the original order, the first character with count 1.

charswi

Counting each character of "swiss" - the key is the character, the value its count; the second pass finds the first 1 in the original order
main.cpp
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5#include <unordered_map>6using namespace std;7 8int first_unique(const string& s) {9    unordered_map<char, int> cnt;10    for (char c : s)11        cnt[c]++;                            // first pass: count12    for (int i = 0; i < (int)s.size(); i++)13        if (cnt[s[i]] == 1)                  // second pass: in the original order14            return i;15    return -1;16}17 18int main() {19    for (string w : {"leetcode", "loveleetcode", "aabb"})20        cout << w << ": " << first_unique(w) << "\n";21 22    vector<string> words = {"to", "be", "or", "not", "to", "be", "to"};23    unordered_map<string, int> freq;24    for (const string& w : words)25        freq[w]++;26    vector<pair<int, string>> v;             // take them out and sort: the table's order is not fixed27    for (const auto& kv : freq)28        v.push_back({-kv.second, kv.first});    // negate the count: ascending order is then most frequent first29    sort(v.begin(), v.end());30    for (const auto& p : v)31        cout << p.second << " " << -p.first << "\n";32    return 0;33}
Output
leetcode: 0
loveleetcode: 2
aabb: -1
to 3
be 2
not 1
or 1

To print word frequencies by count, take the (count, word) pairs out into a vector and sort it, ties going alphabetically, and every run prints the same thing. Printing straight from freq gives an order that depends on the buckets; you can't rely on it. When the key range is small, an array is a hash table: there are only 256 characters, so int cnt[256] = {0} with cnt[(unsigned char)c]++ is faster, and h(c) = c never collides.

Choose one

An array can hold any number from −10⁹ to 10⁹, and you need to know whether there is a duplicate. What should you use?

Exercise 2

The most common number

Fill in most_common - count each number with an unordered_map<int, int> and return the one that appears most often; on a tie, the smaller one. It prints "number count".

It should print
1 3
7 2
exercise2.cpp
1#include <iostream>2#include <vector>3#include <unordered_map>4using namespace std;5 6int most_common(const vector<int>& a, int& times) {7    unordered_map<int, int> cnt;8    // first pass: cnt[x]++9    int best = 0;10    times = 0;11    // second pass: walk cnt; if kv.second is larger, or equal with a smaller kv.first, take it12    return best;13}14 15int main() {16    int t;17    int x = most_common({4, 1, 4, 2, 1, 4, 3, 1}, t);18    cout << x << " " << t << "\n";19    x = most_common({7, 7, 5}, t);20    cout << x << " " << t << "\n";21    return 0;22}
Output
Press Run or Ctrl+Enter

Pattern 3: grouping by a key

Group anagrams: eat, tea, ate in one group, tan, nat in another, bat on its own. The key idea is to compute a key that comes out the same for every word in a group: sort the letters, and eat, tea, ate all become aet. Then put each word into its bucket of an unordered_map<string, vector<string>> by that key:

sorted lettersaetantabt

Grouping by sorted letters - words with the same key go into the same bucket, and each bucket is one group
main.cpp
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5#include <unordered_map>6using namespace std;7 8int main() {9    vector<string> words = {"eat", "tea", "tan", "ate", "nat", "bat"};10    unordered_map<string, vector<string>> groups;11    vector<string> order;                    // the order each key first appears in12    for (const string& w : words) {13        string key = w;14        sort(key.begin(), key.end());        // eat → aet15        if (!groups.count(key)) order.push_back(key);16        groups[key].push_back(w);            // a missing key: [] first puts in an empty vector17    }18    for (const string& k : order) {19        cout << k << ":";20        for (const string& w : groups[k]) cout << " " << w;21        cout << "\n";22    }23 24    // another key: how often each of the 26 letters appears, kept in a 26-char string, no sorting, O(k)25    unordered_map<string, int> groups2;26    for (const string& w : words) {27        string key(26, 0);28        for (char c : w) key[c - 'a']++;29        groups2[key]++;30    }31    cout << groups2.size() << " groups\n";32    return 0;33}
Output
aet: eat tea ate
ant: tan nat
abt: bat
3 groups

The first time groups[key] meets a key it puts in an empty vector, so you can push_back straight away. To print the groups in the order their words first appear, an order vector records when each key was first seen, which is more reliable than walking groups. The second key is the 26 letter counts: O(k) to compute, no sorting. It is kept as a string because vector<int> has no ready-made hash and can't be an unordered_map key (it can be a map key).

PatternWhat the table holdsTypical problemsTime
look up while walkingvalue → index (or an unordered_set of values)two sum, contains duplicate, longest substring without repeatsO(n)
countingthing → counttop k frequent, anagrams, first non-repeating characterO(n)
grouping by a keycomputed key → vectorgroup anagrams, sort into groups by some propertyO(n) × computing the key

In interviews: state the O(n²) brute force first, then "remember what I've seen in an unordered_map, for O(n) time and O(n) space": a trade of space for time. For a grouping problem the key point is one sentence saying "which things should compute the same key". To ask whether something is there, use count / find, not [].

Choose one

Group listen, silent, enlist, google by anagram, using "the letters sorted" as the key. What is the key of listen?

Exercise 3

Group anagrams

Fill in the loop - sort each word's letters to get its key, record the key in order the first time it appears, then put the word into groups[key]. One line per group, in order.

It should print
listen silent enlist
google gogole
cat act
exercise3.cpp
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5#include <unordered_map>6using namespace std;7 8int main() {9    vector<string> words = {"listen", "google", "silent", "enlist", "gogole", "cat", "act"};10    unordered_map<string, vector<string>> groups;11    vector<string> order;12    for (const string& w : words) {13        // string key = w; sort key; if groups has no key yet, order.push_back(key); groups[key].push_back(w)14    }15    for (const string& k : order) {16        for (int i = 0; i < (int)groups[k].size(); i++)17            cout << (i ? " " : "") << groups[k][i];18        cout << "\n";19    }20    return 0;21}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Three hash table patterns

  • two sum: look up target − x first, then insert x; O(n²) becomes O(n)
  • counting: unordered_map<K, int> and cnt[x]++; a small key range just needs an array
  • grouping: compute a key that is the same within a group, fill an unordered_map<key, vector>
  • ask with count / find; for ordered output, sort first or record the order
1unordered_map<int, int> seen;2for (int j = 0; j < n; j++) {3    auto it = seen.find(target - a[j]);4    if (it != seen.end()) return {it->second, j};5    seen[a[j]] = j;6}

Chapter 3 quick check

Five questions: choosing the table size, string hashing, linear probing, deleting, and unordered_map's []. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

The 12 keys 6, 12, …, 72 go into a table with m = 12. How many cells get used?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<bool> used(12, false);7    int slots = 0;8    for (int k = 6; k <= 72; k += 6) {9        if (!used[k % 12]) slots++;10        used[k % 12] = true;11    }12    cout << slots << "\n";13    return 0;14}
Guess the outputA wrong guess is fine

'a' is 97 and 'b' is 98. h = h * 31 + c over "ab" prints what?

1#include <iostream>2#include <string>3using namespace std;4 5int main() {6    unsigned h = 0;7    for (char c : string("ab"))8        h = h * 31 + c;9    cout << h << "\n";10    return 0;11}
Guess the outputA wrong guess is fine

Table size 7, linear probing, insert 6 13 20 in order. Which cell does 20 go in?

1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 7;6vector<int> t(M, -1);7 8int insert(int k) {9    for (int i = 0; i < M; i++) {10        int p = (k % M + i) % M;11        if (t[p] == -1) { t[p] = k; return p; }12    }13    return -1;14}15 16int main() {17    insert(6);18    insert(13);19    cout << insert(20) << "\n";20    return 0;21}
Guess the outputA wrong guess is fine

3 10 17 all leave remainder 3 and sit in cells 3, 4, 5 by linear probing. Empty 10's cell, then search for 17. What prints?

1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 7;6vector<int> t(M, -1);7 8int search(int k) {9    for (int i = 0; i < M; i++) {10        int p = (k % M + i) % M;11        if (t[p] == -1) return -1;12        if (t[p] == k) return p;13    }14    return -1;15}16 17int main() {18    t[3] = 3; t[4] = 10; t[5] = 17;     // placed by linear probing: all % 7 == 319    t[search(10)] = -1;                  // delete 10 by just emptying its cell20    cout << search(17) << "\n";21    return 0;22}
Guess the outputA wrong guess is fine

Only "a" was given a value. What does m.size() print?

1#include <iostream>2#include <string>3#include <unordered_map>4using namespace std;5 6int main() {7    unordered_map<string, int> m;8    m["a"] = 1;9    if (m["b"] > 0)10        m["c"] = 1;11    cout << m.size() << "\n";12    return 0;13}