TExcelTAD

Hash Sets

A hash set is a hash table that stores keys only, without values. It answers one question extremely fast: "is this item in the collection?" Every item appears at most once; adding an item that is already there changes nothing.

Typical uses:

  • Removing duplicates from data.
  • Remembering what you have already seen (visited web pages, visited graph nodes).
  • Fast membership checks: banned words, valid usernames, allowed file types.

Watching a hash set work

Here a 5-bucket set receives some colour names. Adding red a second time finds it already in its bucket and stores nothing, and the lookup for green searches only bucket 4:

Implementation

Our HashSet uses chaining and the lesson's simple hash (sum of character codes). It also grows: when the number of items exceeds the number of buckets (load factor above 1), it doubles the bucket count and re-inserts every item, because each item's bucket depends on the table size.

python · try it yourself
class HashSet:
    def __init__(self, buckets=5):
        self.buckets = [[] for _ in range(buckets)]
        self.count = 0

    def _bucket(self, item):
        return self.buckets[sum(ord(c) for c in item) % len(self.buckets)]

    def add(self, item):
        bucket = self._bucket(item)
        if item in bucket:
            return False
        bucket.append(item)
        self.count += 1
        if self.count > len(self.buckets):
            self._grow()
        return True

    def contains(self, item):
        return item in self._bucket(item)

    def remove(self, item):
        bucket = self._bucket(item)
        if item in bucket:
            bucket.remove(item)
            self.count -= 1

    def _grow(self):
        old = [item for bucket in self.buckets for item in bucket]
        self.buckets = [[] for _ in range(2 * len(self.buckets))]
        for item in old:
            self._bucket(item).append(item)
        print(f"  (grew to {len(self.buckets)} buckets)")

colours = HashSet()
for c in ["red", "blue", "teal", "red", "gold"]:
    print(f"add {c}: {colours.add(c)}")
print(colours.buckets)
print("green?", colours.contains("green"), " gold?", colours.contains("gold"))
colours.remove("teal")
for c in ["pink", "gray", "cyan"]:
    colours.add(c)
print(colours.buckets, colours.count)
add red: True
add blue: True
add teal: True
add red: False
add gold: True
[['red'], [], ['teal', 'gold'], [], ['blue']]
green? False  gold? True
  (grew to 10 buckets)
[[], [], ['gold'], [], ['blue', 'pink'], ['red', 'gray'], [], ['cyan'], [], []] 6

Up to the removal of teal, the buckets are the same as in the animation. Adding the sixth item pushed the load factor over 1, so the set grew to 10 buckets and every item moved to its new bucket (sum mod 10).

Python's set

Python's built-in set is a highly optimised hash set. Its operations correspond directly to set theory:

python · try it yourself
python_devs = {"Ana", "Ben", "Cleo", "Dev"}
rust_devs = {"Cleo", "Eli", "Ana"}

print(sorted(python_devs & rust_devs))   # intersection: both
print(sorted(python_devs | rust_devs))   # union: either
print(sorted(python_devs - rust_devs))   # difference: Python only
print(sorted(python_devs ^ rust_devs))   # symmetric difference: exactly one
print("Eli" in rust_devs, "Eli" in python_devs)
['Ana', 'Cleo']
['Ana', 'Ben', 'Cleo', 'Dev', 'Eli']
['Ben', 'Dev']
['Ben', 'Dev', 'Eli']
True False

Note: A set has no order. Printing a set of strings can show a different order in different runs, because Python randomises string hashes per process. Use sorted() whenever the order of output matters.

Removing duplicates, keeping order

set(items) removes duplicates but loses the order. To keep the first occurrence of each item in order, combine a set (for the "seen?" check) with a list (for the order). Each check is O(1), so the whole thing is O(n):

python · try it yourself
def unique_in_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

visits = ["home", "news", "home", "sport", "news", "weather"]
print(unique_in_order(visits))
print(list(dict.fromkeys(visits)))   # the same trick using dict ordering
['home', 'news', 'sport', 'weather']
['home', 'news', 'sport', 'weather']

Set vs list for membership

How much faster is in on a set? Let's count the comparisons a list needs versus the single bucket a set checks:

python · try it yourself
def list_checks(items, target):
    for i, x in enumerate(items):
        if x == target:
            return i + 1
    return len(items)

ids = list(range(0, 200_000, 2))       # 100,000 even numbers
id_set = set(ids)
for target in [10, 150_000, 199_999]:
    print(f"{target:>7}: list compares {list_checks(ids, target):>6} items, set answers {target in id_set}")
     10: list compares      6 items, set answers True
 150000: list compares  75001 items, set answers True
 199999: list compares 100000 items, set answers False

What can go into a set?

Only hashable items: values whose hash never changes, such as numbers, strings and tuples of hashable items. Lists, dicts and sets are mutable and therefore not hashable; if an item's contents changed, its hash would change and it would be in the "wrong" bucket.

python · try it yourself
points = {(0, 0), (1, 2), (0, 0)}
print(len(points))
try:
    bad = {[1, 2]}
except TypeError as err:
    print("TypeError:", err)
print(frozenset({1, 2}) in {frozenset({2, 1})})
2
TypeError: unhashable type: 'list'
True

Test yourself

What happens when you add an item that is already in a hash set?

  1. It is stored twice
  2. Nothing changes
  3. An error is raised
  4. The old one is removed

Why must every item be re-inserted when a hash set grows?

  1. To sort them
  2. The bucket index depends on the table size, so items move to new buckets
  3. To remove duplicates
  4. It doesn't need to

Which of these can be stored in a Python set?

  1. [1, 2]
  2. {"a": 1}
  3. (1, 2)
  4. {1, 2}