AlgoViz

Sets and maps

easy 16 min

A set stores unique keys and a map stores one value per key.

Video lesson · Chapter 1 of 6

One copy of a word

0:00 / 4:55

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.

Step 1 of 3

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.

FeatureSetMap
StoresUnique keys onlyKey-value pairs
Same key againRejected, size unchangedValue replaced, size unchanged
Insertadd(key)put(key, value), d[key] = value
Look upcontains(key) gives a boolget(key) gives the value or None
Typical useMembership tests, removing duplicatesLookup tables, counting, grouping

The interface

Core operations

OperationMeaningPythonHash-backedTree-backed
insertAdd a key (set) or key-value pair (map)s.add(x), d[k] = vO(1)O(1) avgO(log⁡n)O(\log n)
searchIs the key there?x in s, k in dO(1)O(1) avgO(log⁡n)O(\log n)
getValue for a key (map)d[k], d.get(k)O(1)O(1) avgO(log⁡n)O(\log n)
deleteRemove a keys.discard(x), del d[k]O(1)O(1) avgO(log⁡n)O(\log n)
sizeNumber of keyslen(s)O(1)O(1)O(1)O(1)
iterateVisit every keyfor k in dO(n)O(n), no orderO(n)O(n), sorted
Tree costs assume a balanced tree. A plain BST that has become a chain costs O(n)O(n) per operation.
Python
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']}
Python's built-in set and dict are hash-backed. Counter and defaultdict are dicts with conveniences.
Edit and run it in your browser

Two backings

Hash-backed vs tree-backed

Where a key goes in each backing

A hash table jumps to the right place using arithmetic. A tree narrows down by comparing, which is slower but leaves the keys in order.
FeatureTreeSet / TreeMap (balanced BST)HashSet / HashMap
Time, averageO(log⁡n)O(\log n)O(1)O(1)
Time, worstO(log⁡n)O(\log n) if self-balancingO(n)O(n) if many keys collide
Ordered iterationYes, sortedNo (Python dict: insertion order)
Range queriesYes, O(log⁡n+k)O(\log n + k)No, O(n)O(n) scan
Min and maxO(log⁡n)O(\log n)O(n)O(n)
Floor and ceilingO(log⁡n)O(\log n)O(n)O(n)
Key requirementKeys must be comparableKeys must be hashable
MemoryMore: two child pointers per nodeUsually less, plus spare buckets
kk is the number of keys a range query returns. A plain, unbalanced BST can degrade to O(n)O(n); AVL and red-black trees guarantee O(log⁡n)O(\log n).

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

Seven keys, three levels. Any key is reached in at most 3 comparisons; reading left to right gives 20, 30, 40, 50, 60, 70, 80.

The invariant, at every node v

∀ a∈left(v): a<v.keyand∀ b∈right(v): b>v.key\forall\, a \in \text{left}(v):\ a < v.\text{key} \qquad \text{and} \qquad \forall\, b \in \text{right}(v):\ b > v.\text{key}
It applies recursively to every node, not just the root. Strict inequalities are what make the keys unique: an equal key has nowhere to go, so a set rejects it and a map updates the existing node.
  • 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

Adding 35 to {20, 30, 40, 50, 70}: 35 < 50 go left, 35 > 30 go right, 35 < 40 and the left slot is empty, so 35 becomes the left child of 40.

remove(x): three cases

Removing 30 from the 7-key tree: 30 has two children, its successor is 40, so 40 moves up and the old 40 leaf is cut off. The result is 50 over 40 and 70, with 20 under 40.
Every tree operation is the same walk
  1. 1Comparex against the current key
  2. 2Descendleft if smaller, right if larger
  3. 3Stopon equal or at an empty slot
  4. 4Actattach, report, update or unlink

add, contains, get, put, remove, floor and ceiling differ only in the last box.

Python
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] 6
A complete tree-backed set: iterative add and contains, recursive remove, inorder keys.
Edit and run it in your browser

Complexity

O(log n) when balanced, O(n) when not

Every tree operation walks one path from the root, so its cost is the height hh of the tree. In a perfectly balanced tree, level kk holds 2k2^k nodes, so the height grows only with the logarithm of nn.

Height of a balanced tree

n≤1+2+4+⋯+2h−1=2h−1  ⟹  h≥log⁡2(n+1)  ⟹  hmin⁡=⌈log⁡2(n+1)⌉n \le 1 + 2 + 4 + \dots + 2^{h-1} = 2^h - 1 \;\Longrightarrow\; h \ge \log_2(n + 1) \;\Longrightarrow\; h_{\min} = \lceil \log_2(n+1) \rceil
7 keys fit in 3 levels, 1,023 keys in 10, and a million keys in 20. Self-balancing trees keep hh within a small constant of this (an AVL tree below about 1.44log⁡2n1.44 \log_2 n, a red-black tree below 2log⁡2(n+1)2 \log_2 (n+1)).
OperationPlain BST, averagePlain BST, worstBalanced BST (AVL, red-black)
SearchO(log⁡n)O(\log n)O(n)O(n)O(log⁡n)O(\log n)
InsertO(log⁡n)O(\log n)O(n)O(n)O(log⁡n)O(\log n)
DeleteO(log⁡n)O(\log n)O(n)O(n)O(log⁡n)O(\log n)
Min / maxO(log⁡n)O(\log n)O(n)O(n)O(log⁡n)O(\log n)
Sorted iterationO(n)O(n)O(n)O(n)O(n)O(n)
"Average" means keys inserted in random order, which gives an expected height of O(log⁡n)O(\log n).

Hash-backed

O(1) on average, in no particular order

A hash-backed set or map keeps an array of mm 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

α=nm,E[cost of a lookup]=O(1+α)\alpha = \frac{n}{m}, \qquad \mathbb{E}[\text{cost of a lookup}] = O(1 + \alpha)
The table grows (roughly doubling mm) whenever α\alpha passes a threshold, so α\alpha stays bounded and the average cost stays O(1)O(1). Resizing costs O(n)O(n) once in a while, which is O(1)O(1) amortized per insert. If many keys collide in one bucket, a lookup degrades to O(n)O(n).

Ordered operations

What only a tree can answer

QuestionJava TreeSet / TreeMapPython sortedcontainersCost
Smallest, largest keyfirst(), last()s[0], s[-1]O(log⁡n)O(\log n)
Largest key ≤x\le x (floor)floor(x)s[s.bisect_right(x) - 1]O(log⁡n)O(\log n)
Smallest key ≥x\ge x (ceiling)ceiling(x)s[s.bisect_left(x)]O(log⁡n)O(\log n)
Strictly below / above xxlower(x), higher(x)bisect_left - 1, bisect_rightO(log⁡n)O(\log n)
All keys in [a,b][a, b]subSet(a, true, b, true)s.irange(a, b)O(log⁡n+k)O(\log n + k)
Keys in sorted orderiterationiterationO(n)O(n)
sortedcontainers is a popular pure-Python package (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

floor(45) in {20, 30, 40, 50, 60, 70, 80}: 50 too big, go left; 30 fits, go right; 40 fits better, go right; fall off, answer 40. ceiling mirrors it and gives 50.
Python
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)
With only the standard library: keep a sorted list and use bisect. Lookups are O(log n); inserts are O(n) because the list shifts.
Edit and run it in your browser
Python
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 level
The same with sortedcontainers (install it first). SortedDict keeps keys sorted and still supports d[key].

Set algebra

Union, intersection, difference

The four operations

A∪B={x:x∈A∨x∈B},A∩B={x:x∈A∧x∈B},A∖B={x∈A:x∉B},A△B=(A∪B)∖(A∩B)A \cup B = \{x : x \in A \lor x \in B\}, \quad A \cap B = \{x : x \in A \land x \in B\}, \quad A \setminus B = \{x \in A : x \notin B\}, \quad A \triangle B = (A \cup B) \setminus (A \cap B)
With A={1,2,3}A = \{1, 2, 3\} and B={3,4,5}B = \{3, 4, 5\}: union {1,2,3,4,5}\{1, 2, 3, 4, 5\}, intersection {3}\{3\}, A∖B={1,2}A \setminus B = \{1, 2\}, symmetric difference {1,2,4,5}\{1, 2, 4, 5\}.
OperationPython operatorMethodCost (hash sets)
Uniona | ba.union(b)O(∣A∣+∣B∣)O(|A| + |B|)
Intersectiona & ba.intersection(b)O(min⁡(∣A∣,∣B∣))O(\min(|A|, |B|))
Differencea - ba.difference(b)O(∣A∣)O(|A|)
Symmetric differencea ^ ba.symmetric_difference(b)O(∣A∣+∣B∣)O(|A| + |B|)
Subseta <= ba.issubset(b)O(∣A∣)O(|A|)
Disjointnot (a & b)a.isdisjoint(b)O(min⁡(∣A∣,∣B∣))O(\min(|A|, |B|))
Intersection loops over the smaller set and checks each value in the larger one, so its cost depends only on the smaller side.
Python
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 Bo
Set algebra replaces nested loops. The size of a union follows inclusion-exclusion.
Edit and run it in your browser

Inclusion-exclusion

∣A∪B∣=∣A∣+∣B∣−∣A∩B∣|A \cup B| = |A| + |B| - |A \cap B|
Adding the two sizes counts the shared keys twice, so subtract them once. For A={1,2,3,4}A = \{1, 2, 3, 4\}, B={3,4,5,6}B = \{3, 4, 5, 6\}: 4+4−2=64 + 4 - 2 = 6.

Toolkit

Sets and maps across languages

LanguageHash set / mapTree (sorted) set / map
Pythonset, frozenset, dict, Counter, defaultdictsortedcontainers: SortedSet, SortedDict, SortedList (third party)
JavaHashSet, HashMap, LinkedHashMapTreeSet, TreeMap (red-black tree)
C++std::unordered_set, std::unordered_mapstd::set, std::map (usually red-black)
JavaScriptSet, Map (insertion order)none built in
Gomap[K]V (iteration order randomised)none built in
Python has no tree map in the standard library; in interviews either use sortedcontainers if allowed, or a sorted list with bisect.

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: O(1)O(1) 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

Most problems end at the hash-backed box. Order-dependent questions (next booking, nearest price, k-th smallest in a window) push you to the tree.

Four problems, four picks

  1. 1

    Has any value repeated?

    Only membership matters: a hash set, one pass, O(n)O(n).

  2. 2

    Which two values sum to the target?

    Need the index of a value: a hash dict from value to index, O(n)O(n).

  3. 3

    Can this meeting be booked?

    Need the bookings just before and after the new one: a sorted map by start time, O(log⁡n)O(\log n) per query.

  4. 4

    Show all users with ids 100 to 200, in order

    A range in sorted order: a tree map's range query, O(log⁡n+k)O(\log n + k).

Do

  • Default to set and dict for 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 O(log⁡n)O(\log n).

Avoid

  • Paying O(log⁡n)O(\log n) 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: O(n)O(n) per check where a set is O(1)O(1).

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: O(1)O(1) average insert, search and delete, no order, keys must be hashable. Python's set and dict.
  • Tree-backed: O(log⁡n)O(\log n) 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 O(n)O(n) on sorted inserts; AVL and red-black trees keep the height near log⁡2n\log_2 n.
  • Set algebra: union, intersection (O(min⁡)O(\min)), difference and symmetric difference replace nested loops.

Sources