Inside a set: a map with no values
After this: Follow add, contains and remove through the hash-map table with no values.
On this page · 9 sections · 4 checks
In the last lesson you used a set, and you saw that it answers "is this item here?" quickly, however many items it holds. This lesson looks inside to see how.
The short answer is that a hash set is a hash map with the values taken out. So we begin with a short reminder of how a hash map works. The tutorial Hash Maps & Hashing teaches this slowly, if you would like more detail.
A reminder: where a key goes
A hash map keeps its data in a table of numbered places called . Each entry in the table is a pair: a and a value. To decide which slot a key goes in, a turns the key into a number.
In these tutorials the hash function adds up the code of each letter. Computers store every letter as a number, and that number is its code. Here is where cat goes in a table of 8 slots.
- Find the code of each letter: c is 99, a is 97 and t is 116.
- Add them up: 99 + 97 + 116 = 312.
- Divide by the number of slots and keep the remainder: 312 ÷ 8 = 39, remainder 0. In code this is
312 % 8. - The remainder is the slot number, so
catgoes in slot 0.
The letters of dog add up to 314, and 314 % 8 = 2, so dog goes in slot 2.
The computer can do this calculation again whenever it needs the key, so it goes straight to the right slot. It does not search the table. This is where the speed comes from.
A reminder: two keys in one slot
The key act has the same letters as cat, so it has the same sum, 312, and it also goes in slot 0. Two different keys landing in one slot is called a .
Keys that share a slot are kept in a short list called a . To find a key, the computer goes to its slot, then compares the key with each key in the chain, one at a time. We call this walking the chain.
Take the values away
Think about what the table does to find a key. It hashes the key, goes to a slot and compares keys. It never uses the value to find anything. So a set can leave the values out, and everything else stays the same.
| Slot | In a hash map | In a hash set |
|---|---|---|
| 0 | cat → 1, act → 1 | cat, act |
| 2 | dog → 1 | dog |
The hash function, the slots and the chains are the same, and the items in the set are the keys. This is why a gets the speed of a hash map.
Three operations, one table
A map answers what is stored under this key? A set answers is this key here? Each set operation matches a map operation.
- add matches insert, with no value. Hash the key and go to the slot. Walk the chain to make sure the key is not already there. If it is not, put it at the end of the chain.
- contains matches lookup. Hash the key, go to the slot and walk the chain, comparing keys. In code it is "cat" in ss.contains("cat"). It answers Truetrue or Falsefalse and does not return a value.
- remove matches delete. Find the key in its chain and take it out. The keys behind it move up, so the chain has no gap.
One example, step by step
Collisions still happen in a set. Here is a set with 8 slots, one step at a time.
- Add
cat. It goes to slot 0. The slot is empty, socatgoes straight in. - Add
act. It also goes to slot 0. The computer comparesactwithcat, and they are different. The chain ends there, soactjoins the chain. - Ask "tac" in ss.contains("tac"). The key
tachas the same letters too, so it goes to slot 0. The computer compares it withcat, then withact. Neither matches and the chain ends, so the answer is Falsefalse.
That was two comparisons for a "no". A hash map would make the same two comparisons for the same question.
Chains stay short, so a membership test costs O(1) on average: the number of steps does not grow when the set grows. This needs two things to be true. The hash function must spread the keys across the slots, and the table must grow before it gets crowded.
The code
Here is a small hash set that we write ourselves, so that every step is visible. It is the SimpleHashMap of the Hash Maps tutorial with each pair replaced by a key.
class SimpleHashSet: def __init__(self, capacity=8): self.capacity = capacity self.buckets = [[] for _ in range(capacity)] # each slot holds a chain of keys self.count = 0
def _index(self, key): return sum(ord(ch) for ch in key) % self.capacity # the same hash as the map
def add(self, key): if key in self: # already a member: nothing to do return self.buckets[self._index(key)].append(key) # no value: the key alone self.count += 1
def __contains__(self, key): # enables: "cat" in s bucket = self.buckets[self._index(key)] for stored_key in bucket: # the chain walk, unchanged if stored_key == key: return True return False
def remove(self, key): bucket = self.buckets[self._index(key)] for i, stored_key in enumerate(bucket): if stored_key == key: bucket.pop(i) # the chain closes up self.count -= 1 return True return False # nothing to remove
def __len__(self): # enables: len(s) return self.countimport java.util.ArrayList;import java.util.List;
public class SimpleHashSet { private final int capacity; private final List<List<String>> buckets; // each slot holds a chain of keys private int count = 0;
public SimpleHashSet() { this(8); }
public SimpleHashSet(int capacity) { this.capacity = capacity; this.buckets = new ArrayList<>(); for (int i = 0; i < capacity; i++) buckets.add(new ArrayList<>()); }
private int index(String key) { int sum = 0; for (char ch : key.toCharArray()) sum += ch; // the same hash as the map return sum % capacity; }
public boolean add(String key) { if (contains(key)) return false; // already a member: nothing to do buckets.get(index(key)).add(key); // no value: the key alone count++; return true; // like HashSet.add: true if it was new }
public boolean contains(String key) { List<String> bucket = buckets.get(index(key)); for (String storedKey : bucket) { // the chain walk, unchanged if (storedKey.equals(key)) { return true; } } return false; }
public boolean remove(String key) { List<String> bucket = buckets.get(index(key)); for (int i = 0; i < bucket.size(); i++) { if (bucket.get(i).equals(key)) { bucket.remove(i); // the chain closes up count--; return true; } } return false; // nothing to remove }
public int size() { return count; }}Here is how to read it.
bucketsis the table. It holds one chain for each slot.- _indexindex works out the slot: the sum of the letter codes, then the remainder after dividing by the number of slots.
addfirst asks whether the key is already there. If it is,addstops. This is why adding a key twice stores it once.- The highlighted lines are the membership test. They find the chain, compare each key, and answer yes or no. In Python, the special name __contains__ is what lets you write "cat" in s.
removefinds the key in its chain and takes it out. It answers yes if it removed something and no if the key was not there.countkeeps track of how many keys are stored.
This small version never grows its table. Real hash sets do, as the lesson Growing the table explains.
s = SimpleHashSet()s.add("cat")s.add("act") # same slot as "cat": appended to the chainprint("act" in s) # walks slot 0: compares "cat", then "act"print("tac" in s) # also slot 0, but not in the chainprint(len(s))True False 2
SimpleHashSet s = new SimpleHashSet();s.add("cat");s.add("act"); // same slot as "cat": appended to the chainSystem.out.println(s.contains("act")); // walks slot 0: compares "cat", then "act"System.out.println(s.contains("tac")); // also slot 0, but not in the chainSystem.out.println(s.size());true false 2
Watch it happen
This is the visualizer from the Hash Maps tutorial, set up for a set. There is no value to type, and the buttons read Add, Contains? and Remove. The task has five steps, and the second asks you to predict the slot first.
- Add catAdd cat. The slot is empty, so the key goes straight in. There is no value to type.
- Add act
- Contains? tac
- Contains? act
- Remove act
- 0—
- 1—
- 2—
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 0
- load
- 0.00
- compares
- 0
Check yourself
Compared with a hash map, what changes inside the table when it becomes a set?
What does this print?
s = SimpleHashSet()s.add("cat")s.add("cat")s.add("act")print(len(s), "tac" in s)SimpleHashSet s = new SimpleHashSet();s.add("cat");s.add("cat");s.add("act");System.out.println(s.size() + " " + s.contains("tac"));The set holds cat, act and dog. Which slot does "tac" in ss.contains("tac") go to? (t = 116, a = 97, c = 99)
After add("cat") and add("act"), what does "tac" in ss.contains("tac") do?
Connect
Your language asks a map and a set the same question, and the same kind of walk happens underneath.
d = {"cat": 1, "act": 1} # a map: key → values = {"cat", "act"} # a set: the keys aloneprint("act" in d, "act" in s) # the same question, the same kind of walkprint("tac" in d, "tac" in s)True True False False
Map<String, Integer> d = new HashMap<>(Map.of("cat", 1, "act", 1)); // a map: key → valueSet<String> s = new HashSet<>(Set.of("cat", "act")); // a set: the keys aloneSystem.out.println(d.containsKey("act") + " " + s.contains("act")); // the same question, the same walkSystem.out.println(d.containsKey("tac") + " " + s.contains("tac"));true true false false
Here is that idea in a few lines. PRESENT is the placeholder. add stores the key with PRESENT as its value, and the membership test asks the map whether it has the key.
class SetFromMap: # what Java's HashSet does, in Python PRESENT = True # the dummy value
def __init__(self): self._map = {}
def add(self, key): self._map[key] = SetFromMap.PRESENT
def __contains__(self, key): return key in self._map # containsKey
def __len__(self): return len(self._map)import java.util.HashMap;
public class SetFromMap<E> { // java.util.HashSet, abridged private static final Object PRESENT = new Object(); // the dummy value private final HashMap<E, Object> map = new HashMap<>();
public boolean add(E e) { return map.put(e, PRESENT) == null; } public boolean contains(Object o) { return map.containsKey(o); } public boolean remove(Object o) { return map.remove(o) == PRESENT; } public int size() { return map.size(); }}- Say what a hash set is: the table of a hash map with the values left out.
- Match add, contains and remove to insert, lookup and delete, and follow each one through a chain.
- Explain why cat and act still collide in a set, and count the comparisons a miss takes.