Essential Data Structures home
Hash Set
A collection that remembers only whether something is in it. No values, no order, no duplicates. Just a fast answer to "have I seen this before?"
What it is
A hash set is a hash table with the values taken out. It stores a collection of distinct items, each one once, and its only real question is membership: is this item in the set or not? Adding an item that is already there changes nothing, so duplicates are impossible by construction.
Underneath, it works exactly like a hash table. A hash function turns each item into a bucket number, and the item waits in that bucket. To test membership, the set hashes the item and looks in that one bucket, never scanning the whole collection. When two items land in the same bucket, a collision, the bucket holds a short list of them, just as a hash table does.
The set keeps no order. Items come out in whatever order the buckets happen to hold them, and that order can change when the set grows and rehashes. If the order of items matters to you, a set is the wrong tool.
How it works
Add hashes the item, goes to its bucket, and stores it there if it is not already present. Membership test hashes the item and checks only that bucket. Delete does the same, then removes the item. When the set gets crowded, measured by the load factor (items divided by buckets), it grows: a bigger array is allocated, every item is rehashed into its new bucket, and the old array is dropped.
Sets also do set operations, the same ones from school mathematics. Union gathers everything in either set, intersection keeps only what is in both, and difference keeps what is in one set but not the other. Each of these walks through the items of one set and tests membership in the other, so their cost grows with the size of the sets.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Add | O(1) | O(n) |
| Membership test | O(1) | O(n) |
| Delete | O(1) | O(n) |
| Union, intersection, difference | O(n) | O(n) |
The worst case happens when many items collide into one bucket, so a test degrades to scanning that bucket. A good hash function and timely resizing keep that rare. For a set operation, n is the size of the set being walked.
When to use it, and when not to
Use a hash set when the question is membership or uniqueness: have I seen this word before, is this user already registered, which items appear in both lists, how many distinct visitors came today? Deduplication is its home ground. It is also the fastest way to filter one list against another, by loading one list into a set and testing each item of the second list against it.
Do not use it when you need the items in a particular order, when you need to find the smallest or largest item, or when items need values attached to them. That last case is a hash table, the set's close relative. Do not use it either when items cannot be hashed, such as a list in Python, since the hash function needs a stable hash for every item. And for a tiny collection that is searched rarely, a plain list is simpler and fast enough.
Where you meet it
Everywhere a program asks "already seen?". A spell checker loads its dictionary into a set and tests each word. A web crawler keeps visited URLs in a set so it never fetches the same page twice. A database keeps a set of distinct values for a column. A social app keeps the set of users who liked a post, and a compiler keeps the set of names already declared in a scope.
In Python
seen = {"ada", "cy"} # a set literal, duplicates dropped
seen.add("bob") # add, O(1) on average
seen.add("ada") # already there, nothing changes
print("cy" in seen) # True, membership test, O(1) on average
print("dan" in seen) # False
seen.discard("bob") # delete, no error if absent
visitors = {"ada", "dan", "eli"}
print(seen | visitors) # union
print(seen & visitors) # intersection
print(seen - visitors) # difference
In short: a hash set trades order and values for speed. Give up both, and the question "have I seen this?" becomes nearly instant.
Sources
- Set (abstract data type), Wikipedia
- Python tutorial, Data Structures (sets)
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 11