Sets and maps
easy 16 minA set stores unique keys and a map stores one value per key.
Video lesson · Chapter 1 of 6
One copy of a word
BST sets and maps — Two boards, one train
1:27Reel
Read caption
A stationmaster inserts a duplicate train number, reassigns its platform, and uses sorted keys to answer a ceiling query and an inclusive range query. A set remembers which keys. A map remembers what goes with each key.
How it works
Step through the idea, or press Play.
Pick the contract. A set answers "is x here?"; a map answers "what value goes with x?". Both keep each key once
Understand it
Start here
What sets and maps are
A set is a collection of unique keys: you can add a key, remove it, and ask whether it is there. A map (also called a dictionary or associative array) stores key-value pairs: each key appears once and points to exactly one value. A set is like a guest list (present or absent); a map is like a dictionary (word to definition).
Set
Unique keys only. Answers "is this element in the set?" Example: the set of student ids enrolled in a course.
Map
Key to value. Answers "what value goes with this key?" Example: student id to student name.
Same key twice
A set rejects the second copy. A map replaces the old value with the new one. Neither ever holds a key twice.
| Feature | Set | Map |
|---|---|---|
| Stores | Unique keys only | Key-value pairs |
| Same key again | Rejected, size unchanged | Value replaced, size unchanged |
| Insert | add(key) | put(key, value), d[key] = value |
| Look up | contains(key) gives a bool | get(key) gives the value or None |
| Typical use | Membership tests, removing duplicates | Lookup tables, counting, grouping |
The interface
Core operations
| Operation | Meaning | Python | Hash-backed | Tree-backed |
|---|---|---|---|---|
| insert | Add a key (set) or key-value pair (map) | s.add(x), d[k] = v | avg | |
| search | Is the key there? | x in s, k in d | avg | |
| get | Value for a key (map) | d[k], d.get(k) | avg | |
| delete | Remove a key | s.discard(x), del d[k] | avg | |
| size | Number of keys | len(s) | ||
| iterate | Visit every key | for k in d | , no order | , sorted |
from collections import Counter, defaultdictids = set()ids.add(101); ids.add(50); ids.add(101) # second 101 is ignoredprint(len(ids), 50 in ids, 99 in ids) # 2 True Falseids.discard(99) # no error if absentnames = {101: "Alice", 50: "Bob"}names[150] = "Charlie" # insertnames[50] = "Bobby" # same key: value replacedprint(names.get(999), len(names)) # None 3print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})groups = defaultdict(list)for w in ["eat", "tea", "tan", "ate"]: groups["".join(sorted(w))].append(w)print(dict(groups)) # {'aet': ['eat', 'tea', 'ate'], 'ant': ['tan']}Two backings
Hash-backed vs tree-backed
Where a key goes in each backing
| Feature | TreeSet / TreeMap (balanced BST) | HashSet / HashMap |
|---|---|---|
| Time, average | ||
| Time, worst | if self-balancing | if many keys collide |
| Ordered iteration | Yes, sorted | No (Python dict: insertion order) |
| Range queries | Yes, | No, scan |
| Min and max | ||
| Floor and ceiling | ||
| Key requirement | Keys must be comparable | Keys must be hashable |
| Memory | More: two child pointers per node | Usually less, plus spare buckets |
Tree-backed
The BST property
Think of a binary search tree as the decision tree of a guessing game. At each node you ask one question: is my target bigger or smaller than this key? Every key in a node's left subtree is smaller and every key in its right subtree is larger, so each answer throws away a whole side.
The set {20, 30, 40, 50, 60, 70, 80} as a balanced BST
The invariant, at every node v
Divide and conquer
Each comparison eliminates one subtree, about half the remaining keys in a balanced tree.
Ordered structure
An inorder traversal (left, node, right) visits the keys in sorted order.
Dynamic
Insert and delete relink a few pointers. Nothing shifts, unlike a sorted array.
Flexible keys
Any comparable type works: numbers, strings (alphabetical), tuples, dates.
Tree-backed
Add, contains and remove
add(x) on a set, put(k, v) on a map
remove(x): three cases
- 1Comparex against the current key
- 2Descendleft if smaller, right if larger
- 3Stopon equal or at an empty slot
- 4Actattach, report, update or unlink
add, contains, get, put, remove, floor and ceiling differ only in the last box.
class Node: def __init__(self, key): self.key, self.left, self.right = key, None, Noneclass BSTSet: def __init__(self): self.root, self.size = None, 0 def add(self, key): if self.root is None: self.root = Node(key); self.size += 1; return True curr = self.root while True: if key == curr.key: return False # duplicate side = "left" if key < curr.key else "right" nxt = getattr(curr, side) if nxt is None: setattr(curr, side, Node(key)); self.size += 1; return True curr = nxt def contains(self, key): curr = self.root while curr and curr.key != key: curr = curr.left if key < curr.key else curr.right return curr is not None def remove(self, key): def rem(node, key): if node is None: return None, False if key < node.key: node.left, ok = rem(node.left, key); return node, ok if key > node.key: node.right, ok = rem(node.right, key); return node, ok if node.left is None: return node.right, True if node.right is None: return node.left, True succ = node.right while succ.left: succ = succ.left node.key = succ.key node.right, _ = rem(node.right, succ.key) return node, True self.root, ok = rem(self.root, key) self.size -= ok return ok def keys(self): out = [] def inorder(n): if n: inorder(n.left); out.append(n.key); inorder(n.right) inorder(self.root) return outs = BSTSet()for x in [50, 30, 70, 20, 40, 60, 80]: s.add(x)print(s.add(30), s.contains(40), s.contains(65)) # False True Falses.remove(30)print(s.keys(), s.size) # [20, 40, 50, 60, 70, 80] 6Complexity
O(log n) when balanced, O(n) when not
Every tree operation walks one path from the root, so its cost is the height of the tree. In a perfectly balanced tree, level holds nodes, so the height grows only with the logarithm of .
Height of a balanced tree
| Operation | Plain BST, average | Plain BST, worst | Balanced BST (AVL, red-black) |
|---|---|---|---|
| Search | |||
| Insert | |||
| Delete | |||
| Min / max | |||
| Sorted iteration |
Hash-backed
O(1) on average, in no particular order
A hash-backed set or map keeps an array of buckets. A key goes to bucket hash(key) % m, so finding it means one arithmetic step plus a short scan of that bucket. Python's set and dict work this way; the details of hash functions, collisions and resizing are in hashing in practice.
Load factor and expected cost
Ordered operations
What only a tree can answer
| Question | Java TreeSet / TreeMap | Python sortedcontainers | Cost |
|---|---|---|---|
| Smallest, largest key | first(), last() | s[0], s[-1] | |
| Largest key (floor) | floor(x) | s[s.bisect_right(x) - 1] | |
| Smallest key (ceiling) | ceiling(x) | s[s.bisect_left(x)] | |
| Strictly below / above | lower(x), higher(x) | bisect_left - 1, bisect_right | |
| All keys in | subSet(a, true, b, true) | s.irange(a, b) | |
| Keys in sorted order | iteration | iteration |
pip install sortedcontainers); its SortedList, SortedSet and SortedDict are built on sorted lists of lists rather than a tree, with the same practical costs.floor(x): one walk, remembering the best candidate
import bisectkeys = [20, 30, 40, 50, 60, 70, 80] # kept sorteddef floor(x): i = bisect.bisect_right(keys, x) return keys[i - 1] if i else Nonedef ceiling(x): i = bisect.bisect_left(keys, x) return keys[i] if i < len(keys) else Nonedef in_range(a, b): return keys[bisect.bisect_left(keys, a):bisect.bisect_right(keys, b)]print(floor(45), ceiling(45)) # 40 50print(floor(10), ceiling(90)) # None Noneprint(in_range(35, 65)) # [40, 50, 60]bisect.insort(keys, 45) # insert and keep sortedprint(keys)from sortedcontainers import SortedSet, SortedDicts = SortedSet([50, 30, 70, 20, 40])s.add(35)print(list(s)) # [20, 30, 35, 40, 50, 70]print(s[0], s[-1]) # 20 70print(list(s.irange(30, 45))) # [30, 35, 40]prices = SortedDict({101.5: 300, 99.0: 120, 100.25: 80})print(prices.peekitem(0)) # (99.0, 120): lowest price levelprint(prices.peekitem(-1)) # (101.5, 300): highest price levelSet algebra
Union, intersection, difference
The four operations
| Operation | Python operator | Method | Cost (hash sets) |
|---|---|---|---|
| Union | a | b | a.union(b) | |
| Intersection | a & b | a.intersection(b) | |
| Difference | a - b | a.difference(b) | |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | |
| Subset | a <= b | a.issubset(b) | |
| Disjoint | not (a & b) | a.isdisjoint(b) |
a = {1, 2, 3, 4}b = {3, 4, 5, 6}print(a | b, a & b, a - b, a ^ b)# {1, 2, 3, 4, 5, 6} {3, 4} {1, 2} {1, 2, 5, 6}assert len(a | b) == len(a) + len(b) - len(a & b) # 6 == 4 + 4 - 2liked_by_ann = {"jazz", "rock", "folk"}liked_by_bo = {"rock", "pop"}print(liked_by_ann & liked_by_bo) # {'rock'}: shared tasteprint(sorted(liked_by_ann - liked_by_bo)) # ['folk', 'jazz']: recommend to BoInclusion-exclusion
Toolkit
Sets and maps across languages
| Language | Hash set / map | Tree (sorted) set / map |
|---|---|---|
| Python | set, frozenset, dict, Counter, defaultdict | sortedcontainers: SortedSet, SortedDict, SortedList (third party) |
| Java | HashSet, HashMap, LinkedHashMap | TreeSet, TreeMap (red-black tree) |
| C++ | std::unordered_set, std::unordered_map | std::set, std::map (usually red-black) |
| JavaScript | Set, Map (insertion order) | none built in |
| Go | map[K]V (iteration order randomised) | none built in |
Related structures
AVL tree
A BST that rebalances by rotations so the two subtree heights at every node differ by at most 1.
Red-black tree
A looser balance rule with fewer rotations. Backs Java's TreeMap and C++'s std::map.
Hash map
The unordered alternative: average lookups, keys must be hashable.
Binary heap
A different ordering: only the minimum (or maximum) is cheap to reach. Not a search structure.
Trie
A tree for string keys that branches on characters; great for prefix queries.
B-tree
A wide, shallow search tree tuned for disks. Database indexes are ordered maps built this way.
Choosing
Which one should you use?
Pick the structure
Four problems, four picks
- 1
Has any value repeated?
Only membership matters: a hash
set, one pass, . - 2
Which two values sum to the target?
Need the index of a value: a hash
dictfrom value to index, . - 3
Can this meeting be booked?
Need the bookings just before and after the new one: a sorted map by start time, per query.
- 4
Show all users with ids 100 to 200, in order
A range in sorted order: a tree map's range query, .
Do
- Default to
setanddictfor membership, counting, grouping and dedupe. - Use a tree-backed map when the problem says next, previous, nearest, at least, at most or between.
- Use tuples or frozensets as keys when you need composite keys.
- Mention balancing whenever you mention a BST's .
Avoid
- Paying for a TreeMap when nothing uses the order.
- Assuming a set or dict iterates in sorted order.
- A plain, unbalanced BST on input that may arrive sorted.
- Scanning a list for membership in a loop: per check where a set is .
Recap
Key takeaways
Key points
- A set keeps unique keys; a map keeps one value per key. A set rejects a repeated key, a map replaces its value.
- Hash-backed: average insert, search and delete, no order, keys must be hashable. Python's
setanddict. - Tree-backed: with a balanced BST, keys always sorted, plus min, max, floor, ceiling and ranges. Java TreeMap, Python sortedcontainers.
- The BST property (left smaller, right larger) makes search a binary search and inorder traversal a sorted listing.
- A plain BST degrades to on sorted inserts; AVL and red-black trees keep the height near .
- Set algebra: union, intersection (), difference and symmetric difference replace nested loops.