SC 428 · Introduction to C++ and the STL
// Lecture 5
Sets, Maps and Unordered Maps
Kalp Shah · IIT Gandhinagar · 4 November 2026
Today
How they work, how to use them, then practice
01
How they are built
Balanced search trees and hash tables, in pictures, no code
02
Sets
set and unordered_set: unique values, fast membership checks
03
Maps
map and unordered_map: keys with values, counting, choosing a container
04
Practice
Eight problems, each with a problem slide and a solution slide
SC 428 · Lecture 5 · Practice slides have a blue-grey background
Why
“Have I seen this value before?”
Read n = 10^5 numbers. For each one, check whether it appeared earlier.
Store the values in
Cost of n checks
Steps for n = 10^5
a vector, scanned each time
O(n²)
about 5 × 10^9
a set
O(n log n)
about 1.7 × 10^6
an unordered_set
O(n) on average
about 10^5
Today
Containers built so that finding a value does not mean looking at every value.
SC 428 · Lecture 5 · With about 10^8 simple steps per second, the first row takes close to a minute
01
How they are built
balanced search trees · hash tables · no code
How they are built · Search tree
A binary search tree keeps values in order
The rule
Everything below a node on the left is smaller. Everything below it on the right is larger.
Searching for 6
  1. Start at the top: 8.
  2. 6 is smaller than 8: go left to 3.
  3. 6 is larger than 3: go right. Found.
8
3
10
1
6
14
SC 428 · Lecture 5 · How they are built · Orange: the path followed to find 6
How they are built · Search tree
Inserting walks down, then adds a leaf
Inserting 7
  1. 7 is smaller than 8: go left.
  2. 7 is larger than 3: go right.
  3. 7 is larger than 6: go right. The spot is empty, so 7 goes there.
Nothing else moves. Insert costs the height of the tree, like search.
No duplicates: inserting 6 again finds 6 on the way down and stops.
8
3
10
1
6
14
7
SC 428 · Lecture 5 · How they are built · Dashed: the new node 7
How they are built · Balance
The tree must stay balanced
1
2
3
4
5
Unbalanced: insert 1, 2, 3, 4, 5 in order. Height 5: as slow as a list, O(n).
3
2
5
1
4
Balanced: the same five values. Height 3, so every search is short.
What C++ does
set and map use a red-black tree. After every insert or erase it rotates a few nodes to keep the tree balanced.
The height stays O(log n): a million values need only about 20 to 40 levels.
SC 428 · Lecture 5 · How they are built · Balanced height ≈ log₂ n
How they are built · Order
Reading the tree left to right gives sorted order
For every node
Visit its left branch, then the node itself, then its right branch.
The smallest value is the leftmost node; the largest is the rightmost.
8
3
10
1
6
14
Visit order
1
3
6
8
10
14
SC 428 · Lecture 5 · How they are built · This is why looping over a set or map always gives sorted order
How they are built · Maps
A map is the same tree, with a value in every node
Each node holds a key and its value. The tree is ordered by key only; the value travels with it.
Looking up "mango"
  1. "mango" comes after "kiwi": go right.
  2. "mango" comes before "pear": go left.
  3. Found. Its value is 5.
kiwi : 2
apple : 7
pear : 1
fig : 4
mango : 5
SC 428 · Lecture 5 · How they are built · Keys compare in dictionary order: apple < fig < kiwi < mango < pear
How they are built · Hash table
A hash table jumps straight to a bucket
Key
key % 7
Bucket
15
1
1
22
1
1
9
2
2
31
3
3
40
5
5
To find 22: 22 % 7 = 1, so look only in bucket 1. No other bucket is touched.
0
empty
1
15
→
22
2
9
3
31
4
empty
5
40
6
empty
SC 428 · Lecture 5 · How they are built · Real hash functions scramble keys far better than % 7, and work for strings too
How they are built · Hash table
Collisions, growing, and the worst case
Collisions
15 and 22 both land in bucket 1. The bucket keeps a short list, and a search checks only that list.
Growing
When there are more keys than buckets, the table roughly doubles its buckets and places every key again. Like vector regrowth, this keeps inserts cheap on average.
Worst case
If many keys share one bucket, its list grows long and a search becomes O(n). A good hash function makes this rare.
O(1)
average cost of insert, find and erase
no order
keys come out in bucket order, not sorted
SC 428 · Lecture 5 · How they are built · keys ÷ buckets is called the load factor; C++ grows the table when it passes 1
How they are built · Summary
Tree or hash table: what each gives you
Property
set, map
unordered_set, unordered_map
Built on
balanced search tree
hash table
Order when you loop
sorted by key
no fixed order
insert, find, erase
O(log n)
O(1) on average
Worst case
O(log n)
O(n)
Smallest and largest key
at the ends: quick
must check every key
The key must be
comparable with <
hashable
SC 428 · Lecture 5 · How they are built · int, char, string and pairs work as keys in set and map; int, char and string in the unordered ones
02
Sets
set · unordered_set · unique values, fast membership checks
Sets
A set stores each value once, in order
#include <set> set<int> s; s.insert(5); s.insert(1); s.insert(5);                 // already there: ignored s.insert(3); cout << s.size();            // 3 cout << s.count(3);          // 1: in the set cout << s.count(7);          // 0: not in the set s.erase(1); for (int x : s) {     cout << x << " ";        // 3 5 }
Each value at most once. Inserting a duplicate does nothing.
Always in increasing order, because it is the balanced tree from Part 1.
insert, count, erase: O(log n) each.
SC 428 · Lecture 5 · Sets · A set has no s[i]: loop over it with for (int x : s)
Sets
More ways to use a set
set<string> names = {"Ravi", "Asha", "Ravi"}; cout << names.size();                  // 2 vector<int> v = {4, 2, 4, 1, 2}; set<int> d(v.begin(), v.end());        // {1, 2, 4} cout << *d.begin();                    // 1: smallest cout << *d.rbegin();                   // 4: largest if (d.find(2) != d.end()) {     cout << "2 is in d"; }
From a vector: building a set from v drops the duplicates and sorts in one line.
*d.begin() is the smallest value; *d.rbegin() is the largest.
find returns end() when the value is missing, like the STL find. For a yes/no answer, count is simpler.
SC 428 · Lecture 5 · Sets · Strings are sorted in dictionary order, as in Lecture 3
Sets
unordered_set: the same job on a hash table
#include <unordered_set> unordered_set<int> seen; seen.insert(42); seen.insert(7); seen.insert(42);             // ignored cout << seen.size();         // 2 cout << seen.count(7);       // 1 seen.erase(7); for (int x : seen) {     cout << x << " ";        // order not fixed }
Same functions as set: insert, count, find, erase, size.
O(1) on average instead of O(log n).
No order: the loop order is unpredictable and can change as the set grows. No begin() as smallest.
SC 428 · Lecture 5 · Sets · Use it when the only question is “is it there?”
03
Maps
map · unordered_map · counting · choosing a container
Maps
A map links each key to a value
#include <map> map<string, int> stock; stock["apple"] = 10; stock["mango"] = 4; stock["apple"] += 5;               // 15 cout << stock["mango"];            // 4 cout << stock.size();              // 2 stock.erase("mango"); for (pair<string, int> p : stock) {     cout << p.first << " " << p.second << "\n"; }
map<Key, Value>: each key appears once and has one value.
m[key] reads or changes the value, like indexing a vector with any key.
Looping gives the keys in sorted order. p.first is the key; p.second is the value.
SC 428 · Lecture 5 · Maps · Every operation is O(log n): the map is the balanced tree from Part 1
Maps
Reading a missing key creates it
map<string, int> ages; ages["Asha"] = 20; cout << ages["Ravi"];        // 0, and now "Ravi" exists cout << ages.size();         // 2 if (ages.count("Meera") > 0) {     cout << ages["Meera"]; } else {     cout << "Meera not found"; }
Rule
m[key] on a missing key adds that key with value 0.
To check, use count first, as in the if above.
To count, the rule helps: freq[x]++ works even the first time x is seen.
SC 428 · Lecture 5 · Maps · The same rule holds for unordered_map
Maps
The counting pattern
vector<string> words = {"to", "be", "or", "not", "to", "be"}; map<string, int> freq; int n = words.size(); for (int i = 0; i < n; i++) {     freq[words[i]]++; } for (pair<string, int> p : freq) {     cout << p.first << " " << p.second << "\n"; }
Output
be 2 not 1 or 1 to 2
  • freq[w]++ starts from 0 the first time w is seen.
  • The output is sorted by word because map is a tree.
SC 428 · Lecture 5 · Maps · Lecture 3 counted letters with an array of 26; a map counts anything
Maps
unordered_map: a map on a hash table
#include <unordered_map> unordered_map<string, int> freq; freq["to"]++; freq["be"]++; freq["to"]++; cout << freq["to"];         // 2 cout << freq.count("or");   // 0 // prints "to 2" and "be 1", in no fixed order for (pair<string, int> p : freq) {     cout << p.first << " " << p.second << "\n"; }
Same use as map: [], count, erase, size.
O(1) on average per operation.
No order: keys come out in bucket order, not sorted.
SC 428 · Lecture 5 · Maps · The missing-key rule still applies: freq["or"] would create "or"
Maps · Choosing
Which container should I use?
You need
Use
“Is x there?” and nothing else
unordered_set
Unique values in sorted order
set
Smallest or largest of a changing collection
set
A value for each key, fastest lookups
unordered_map
A value for each key, keys in sorted order
map
Positions 0 to n − 1, duplicates allowed
vector
SC 428 · Lecture 5 · Maps · When unsure, the ordered version is always correct; it is just a little slower
Maps · Costs
What each operation costs
Operation
vector
set, map
unordered_set, unordered_map
Add a value
O(1) at the end
O(log n)
O(1) on average
Is x there?
O(n)
O(log n)
O(1) on average
Erase x
O(n)
O(log n)
O(1) on average
Loop in sorted order
sort first: O(n log n)
O(n)
not possible
Smallest value
O(n)
O(1): *s.begin()
O(n)
SC 428 · Lecture 5 · Maps · Headers: <set>, <map>, <unordered_set>, <unordered_map>
04
Practice
eight problems · each with a solution slide
Practice P1 · Problem
uses: set
Distinct values, sorted
Task
Read n, then n integers.
Print how many different values there are. Then print each different value once, in increasing order.
Example
Input: 7 4 2 4 1 2 4 9 Output: 4 1 2 4 9
Hint: a set ignores duplicates and keeps its values sorted.
SC 428 · Lecture 5 · Practice
Practice P1 · Solution
code goes inside main(), with <iostream> and <set>
Distinct values, sorted
int n; cin >> n; set<int> values; for (int i = 0; i < n; i++) {     int x;     cin >> x;     values.insert(x); } cout << values.size() << "\n"; for (int x : values) {     cout << x << " "; }
How it works
  1. Repeated values are ignored by insert, so the set holds 1, 2, 4, 9.
  2. size() is the number of different values.
  3. The loop visits them in increasing order.
SC 428 · Lecture 5 · Practice · n inserts at O(log n) each: O(n log n)
Practice P2 · Problem
uses: unordered_set
First repeated value
Task
Read n, then n integers, one at a time.
Print the first value that appears for a second time. If no value repeats, print -1.
Examples
6 3 8 5 8 3 1 -> 8 4 1 2 3 4     -> -1
Hint: keep every value seen so far, and check each new one against them.
SC 428 · Lecture 5 · Practice
Practice P2 · Solution
code goes inside main(), with <iostream> and <unordered_set>
First repeated value
int n; cin >> n; unordered_set<int> seen; int answer = -1; for (int i = 0; i < n; i++) {     int x;     cin >> x;     if (answer == -1 && seen.count(x) > 0) {         answer = x;     }     seen.insert(x); } cout << answer << "\n";
How it works
  1. seen holds every value read so far.
  2. If x is already in seen, it is a repeat.
  3. answer == -1 keeps only the first repeat.
With a vector: each check scans all earlier values, O(n²). Here each check is O(1) on average.
SC 428 · Lecture 5 · Practice · O(n) on average
Practice P3 · Problem
uses: map, counting pattern
Word frequency
Task
Read n, then n words.
Print each different word with the number of times it appears, in alphabetical order.
Example
Input: 6 to be or not to be Output: be 2 not 1 or 1 to 2
Hint: which container counts things and keeps its keys sorted?
SC 428 · Lecture 5 · Practice
Practice P3 · Solution
code goes inside main(), with <iostream>, <string> and <map>
Word frequency
int n; cin >> n; map<string, int> freq; for (int i = 0; i < n; i++) {     string word;     cin >> word;     freq[word]++; } for (pair<string, int> p : freq) {     cout << p.first << " " << p.second << "\n"; }
How it works
  1. freq[word]++ adds the word with count 0 the first time, then adds 1.
  2. map keeps the words in alphabetical order.
  3. Each element is a pair: the word and its count.
SC 428 · Lecture 5 · Practice · O(n log n)
Practice P4 · Problem
uses: map, best so far
Most frequent value
Task
Read n, then n integers, each up to 10^9.
Print the value that appears most often. If several tie, print the smallest of them.
Example
Input: 8 3 1 3 2 1 3 2 2 Output: 2
Hint: count first, then find the largest count. Values up to 10^9 are too big for a counting array.
SC 428 · Lecture 5 · Practice
Practice P4 · Solution
code goes inside main(), with <iostream> and <map>
Most frequent value
Part 1 · count
int n; cin >> n; map<int, int> freq; for (int i = 0; i < n; i++) {     int x;     cin >> x;     freq[x]++; }
Counts: 1 → 2, 2 → 3, 3 → 3.
Part 2 · largest count
int best = 0; int bestCount = 0; for (pair<int, int> p : freq) {     if (p.second > bestCount) {         best = p.first;         bestCount = p.second;     } } cout << best << "\n";
Ties: map visits keys from smallest up, and > keeps the first one.
SC 428 · Lecture 5 · Practice · O(n log n)
Practice P5 · Problem
uses: set, count
Values in both lists
Task
Read n and a first list of n integers, then m and a second list of m integers.
Print every value that appears in both lists, once each, in increasing order.
Example
Input: 5 4 1 7 4 9 4 9 4 2 4 Output: 4 9
Hint: store the first list in a set, then check each value of the second list against it.
SC 428 · Lecture 5 · Practice
Practice P5 · Solution
code goes inside main(), with <iostream> and <set>
Values in both lists
Part 1 · the first list
int n; cin >> n; set<int> first; for (int i = 0; i < n; i++) {     int x;     cin >> x;     first.insert(x); }
Why a set for common too? A value seen twice in the second list is still stored once, and the output comes out sorted.
Part 2 · check the second list
int m; cin >> m; set<int> common; for (int i = 0; i < m; i++) {     int x;     cin >> x;     if (first.count(x) > 0) {         common.insert(x);     } } for (int x : common) {     cout << x << " "; }
SC 428 · Lecture 5 · Practice · O((n + m) log n)
Practice P6 · Problem
uses: unordered_set
Two values with a given sum
Task
Read n and a target, then n integers.
Print YES if two values at different positions add up to the target. Otherwise print NO.
Examples
5 9 2 7 11 15 1 -> YES 3 10 5 1 2       -> NO
Hint: for each x, the partner it needs is target − x. Has that partner already appeared?
SC 428 · Lecture 5 · Practice
Practice P6 · Solution
code goes inside main(), with <iostream> and <unordered_set>
Two values with a given sum
int n, target; cin >> n >> target; unordered_set<int> seen; bool found = false; for (int i = 0; i < n; i++) {     int x;     cin >> x;     if (seen.count(target - x) > 0) {         found = true;     }     seen.insert(x); } if (found) {     cout << "YES\n"; } else {     cout << "NO\n"; }
How it works
  1. Target 9: read 2, it needs 7, not seen yet.
  2. Read 7, it needs 2: 2 is in seen. YES.
Check before insert, so a single 5 is never paired with itself for target 10.
SC 428 · Lecture 5 · Practice · O(n) on average, instead of O(n²) for all pairs
Practice P7 · Problem
uses: unordered_map, count
Phone book
Task
Read n lines, each a name and a number. Then read q names.
For each name, print its number, or Not found if it is not in the book.
Example
3 Asha 1234 Ravi 5678 Meera 9012 2 Ravi Zoya Output: 5678 Not found
Hint: a map from name to number. Watch out for the [] trap.
SC 428 · Lecture 5 · Practice
Practice P7 · Solution
inside main(), with <iostream>, <string> and <unordered_map>
Phone book
Part 1 · build the book
int n; cin >> n; unordered_map<string, string> phone; for (int i = 0; i < n; i++) {     string name, number;     cin >> name >> number;     phone[name] = number; }
Numbers as strings: they can be long or start with 0, and we never do arithmetic on them.
Part 2 · answer the queries
int q; cin >> q; for (int i = 0; i < q; i++) {     string name;     cin >> name;     if (phone.count(name) > 0) {         cout << phone[name] << "\n";     } else {         cout << "Not found\n";     } }
count before [], so asking for Zoya does not add her to the book.
SC 428 · Lecture 5 · Practice · O(n + q) on average
Practice P8 · Problem
uses: unordered_map, two passes
First character that appears once
Task
Read one word.
Print the first character that appears exactly once in it. If every character repeats, print None.
Examples
swiss -> w level -> v aabb  -> None
Hint: you cannot know a character is unique until you have seen the whole word. Count first, then look.
SC 428 · Lecture 5 · Practice
Practice P8 · Solution
inside main(), with <iostream>, <string> and <unordered_map>
First character that appears once
Pass 1 · count every character
string s; cin >> s; unordered_map<char, int> freq; int n = s.length(); for (int i = 0; i < n; i++) {     freq[s[i]]++; }
For "swiss": s → 3, w → 1, i → 1.
Pass 2 · scan the word in order
bool found = false; for (int i = 0; i < n; i++) {     if (freq[s[i]] == 1) {         cout << s[i] << "\n";         found = true;         break;     } } if (!found) {     cout << "None\n"; }
Loop over the string: the map forgets the word’s order.
SC 428 · Lecture 5 · Practice · Two passes of n steps: O(n) on average
Recap
Six things to remember from today
Trees
set and map are balanced search trees: O(log n), always sorted.
Hash tables
unordered_set and unordered_map: O(1) on average, no order.
Sets
Each value once. count tells you whether a value is there.
Maps
Key to value. Looping gives pairs: p.first is the key, p.second the value.
The [] trap
m[key] on a missing key creates it with 0. Check with count first.
Choosing
Need order? Use the tree. Only lookups? Use the hash table.