AlgoViz

Sets and maps

easy 16 min

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

See it run

Add, find, remove, put and get on a tree-backed set and map, read the keys back in sorted order, then compare a hash-backed set and set algebra.

Operations

Add (set)

Insert a value into a BST-backed set. Walk down by comparing, attach a new leaf at the empty spot, and reject a value that is already there.

Step 1 of 7

The set before

5030204070

size 5

The set holds {20, 30, 40, 50, 70}, stored as a BST: every key on the left of a node is smaller, every key on the right is larger. We run add(35).

Step 1: The set before

def add(self, val):    if self.root is None:        self.root = Node(val)        return True    curr = self.root    while True:        if val < curr.val:            if curr.left is None:                curr.left = Node(val)                return True            curr = curr.left        elif val > curr.val:            if curr.right is None:                curr.right = Node(val)                return True            curr = curr.right        else:            return False        # duplicate: a set keeps one copy
Time
O(log n) balanced, O(n) skewed
Space
O(1) iterative
vs hash set
O(1) average
vs sorted list
O(n) shift

Sets reject duplicates: when val == curr.val, return False. The BST ordering is what makes the duplicate easy to find.

In the real world

The same sets and maps doing real jobs. Pick one and step through it.

Strings are compared alphabetically, so a set of words is a BST in dictionary order and reads back sorted.

Step 1 of 5

mango becomes the root

mango

The first word inserted, mango, becomes the ROOT. Strings compare letter by letter, like a dictionary.

Step 1: mango becomes the root

words = ["mango", "apple", "zebra", "banana", "orange"]s = BSTSet()for w in words:    s.add(w)           # compared alphabeticallyprint(s.keys())# ['apple', 'banana', 'mango', 'orange', 'zebra']

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Writing {} for an empty set

    critical

    In Python {} is an empty dict, not an empty set. Calling .add on it raises AttributeError, and membership tests check keys of a dict.

    Wrong
    seen = {}seen.add(3)        # AttributeError: 'dict' has no attribute 'add'
    Right
    seen = set()seen.add(3)        # {3}
  • Using a mutable value as a key

    critical

    Hash-backed sets and maps need keys whose hash never changes. Lists are unhashable; and a key mutated after insertion would sit in the wrong bucket or tree position. Remove it, change it, re-add it.

    Wrong
    visited = set()visited.add([1, 2])     # TypeError: unhashable type: 'list'
    Right
    visited = set()visited.add((1, 2))     # tuples are immutable and hashable
  • Expecting sorted order from a set or dict

    major

    A Python set has no defined order, and a dict keeps insertion order, not sorted order. If you need keys in order, sort them or use a tree-backed structure such as SortedDict.

    Wrong
    scores = {"cy": 3, "ann": 9, "bo": 5}first = next(iter(scores))     # "cy": insertion order, not "ann"
    Right
    scores = {"cy": 3, "ann": 9, "bo": 5}first = min(scores)            # "ann"for name in sorted(scores):    # ann, bo, cy    print(name, scores[name])
  • Paying for order you do not use

    major

    A tree-backed map costs O(log n) per operation. If nothing needs sorted iteration, min, max, floor, ceiling or ranges, a hash map does the same job in O(1) average.

    Wrong
    from sortedcontainers import SortedDictcounts = SortedDict()          # order never usedfor w in words:    counts[w] = counts.get(w, 0) + 1
    Right
    from collections import Countercounts = Counter(words)        # hash-backed, O(1) average per word
  • set.remove on a missing value

    minor

    remove raises KeyError when the value is absent. discard removes it if present and does nothing otherwise.

    Wrong
    tags = {"a", "b"}tags.remove("c")      # KeyError: 'c'
    Right
    tags = {"a", "b"}tags.discard("c")     # no error
  • Changing a set while looping over it

    major

    Adding or removing elements during iteration raises RuntimeError (set changed size during iteration). Loop over a copy, or build a new set with a comprehension.

    Wrong
    nums = {1, 2, 3, 4}for x in nums:    if x % 2 == 0:        nums.remove(x)    # RuntimeError
    Right
    nums = {1, 2, 3, 4}nums = {x for x in nums if x % 2 != 0}   # {1, 3}

Interview tips

  • How to explain it

    • A set stores unique keys and answers "is x in here?". A map stores key-value pairs and answers "what value goes with x?".
    • Two backings: a hash table gives O(1) average with no order; a balanced BST gives O(log n) with sorted order and range queries.
    • Say it in one line: use TreeSet or TreeMap when you need sorted order or floor, ceiling and ranges; otherwise HashSet or HashMap is faster.
    • Always mention that a plain BST degrades to O(n) on sorted input, and that AVL or red-black balancing fixes it.
  • When to reach for each

    • Hash set: membership, dedupe, seen-before checks, set algebra (common, missing, unique).
    • Hash map: counting, grouping, index lookup, caching (Two Sum, Group Anagrams, LRU cache).
    • Tree set or map: sorted iteration, nearest key, booking intervals, sliding-window order statistics (My Calendar, Contains Duplicate III).
    • Know the follow-ups for the tree side: kth smallest, validate a BST, lowest common ancestor.
  • Memory tricks

    • LEFT-LESS, RIGHT-GREATER: left children are smaller than the parent, right children larger.
    • The library story: at each shelf, earlier letters go left and later letters go right. Keep asking "earlier or later?" until you find the book.
    • Rhyme: "Less goes left, more goes right, search in log time, day or night."
    • Set rejects, map replaces: the same key a second time is refused by a set and overwrites the value in a map.
  • Patterns behind the code

    • Binary search logic: every comparison throws away one subtree.
    • Recursive tree traversal: solve the left subtree, the node, the right subtree.
    • Node-based structure: insert and delete relink pointers; nothing shifts like it would in a sorted array.
    • Return the modified subtree: recursive remove returns the new root of each subtree so parents can relink.