Design HashSet

Build a set of integers from an array of buckets, a remainder that picks one, and a list in each.

Build a set of whole numbers, a class called MyHashSet, without using Java's ready-made hash tables such as HashSet or HashMap. It needs three methods: add(key) puts a key into the set, remove(key) takes it out (and does nothing if the key is not there), and contains(key) returns whether the key is in the set. A set holds each key at most once. Keys are between 0 and 1,000,000, and there are at most 10,000 calls.

Example
add(1), add(2)
contains(1) returns true
contains(3) returns false
add(2)
contains(2) returns true
remove(2)
contains(2) returns false
Solution

The Idea

A set works like a guest list at a door. A name is either on the list or not, and writing the same name twice changes nothing. The three methods are the three things the doorkeeper does: add a name, cross one off, and check whether a name is there.

Look at the example. After add(1) and add(2), the set holds 1 and 2, so contains(1) is true and contains(3) is false. The second add(2) changes nothing, because 2 is already in. After remove(2), contains(2) is false.

The plainest way to keep the keys is one list, and that handles the example. But contains then has to read the list from start to end, and with 10,000 keys that is up to 10,000 comparisons on every call. Could contains know where to look, without reading everything?

It can, if every key has a fixed place that the key itself decides. Split the storage into many small lists, called buckets, and choose a key's bucket with key % 10007, the remainder after dividing the key by 10007. The same key always gives the same remainder, so add and contains always go to the same bucket.

An array of 10007 buckets. Bucket 1 holds a list with 1 and 10008, bucket 2 holds 2, the rest are empty. contains(10008) computes 10008 % 10007 = 1 and searches only bucket 1.

Look at the picture. There are 10007 buckets, numbered 0 to 10006. Key 1 went into bucket 1, and key 2 into bucket 2. Key 10008 also went into bucket 1, because 10008 % 10007 is 1. Two keys sharing a bucket is called a collision, and both keys simply sit in that bucket's list.

To answer contains(10008), the set computes 1 and searches only bucket 1, which holds two keys instead of all of them. That is what a hash set is: an array of small buckets, and a rule that turns a key into a bucket number, called the hash function. Here the hash function is key % 10007.

Solution Approach

Turning that idea into code means settling three things: how many buckets there are, what each bucket is, and how each method uses its bucket.

How many buckets

How many buckets should there be? With one bucket we are back to a single list. With 1,000,001 buckets, one for every possible key, each bucket would hold at most one key. A boolean[1000001] array does the same job more simply: true at index k means k is in the set. That is a valid answer here, and every call is a single step. But it reserves a slot for every possible key even when only a few are stored, and it stops working when keys have no small upper limit.

There are at most 10,000 calls, so at most 10,000 keys, and 10007 buckets is about one bucket per key. The buckets stay short as long as the keys spread out. 10007 is a prime number, which helps when keys follow a pattern. Take the 1,001 multiples of 1000 from 0 to 1,000,000: with 10000 buckets every remainder is a multiple of 1000, so they crowd into just 10 buckets. With 10007 buckets they land in 1,001 different ones.

What each bucket is

What should a bucket be? A LinkedList<Integer>, the list class from java.util, which grows when keys collide and can drop a key from anywhere. The problem only rules out ready-made hash tables, so a list is fine. Keeping the colliding keys of each bucket in a list like this is called separate chaining.

A bucket's list is created only when its first key arrives. Until then its slot in the array is null, so the empty buckets cost nothing beyond the array itself.

What each method does

Every method starts by computing the bucket. add searches that bucket and appends the key only if it is not there yet, which is why the second add(2) changes nothing. remove deletes the key from the bucket. contains returns whether the bucket holds the key. A bucket that was never created holds nothing, so remove and contains check for null first instead of creating an empty list.

Java Solution

The class has these parts:

  • SIZE: the number of buckets, 10007.
  • buckets: the array of buckets. Each slot is a LinkedList<Integer>, or null until its first key arrives.
  • index(key): the hash function, key % SIZE, which picks the bucket.
  • add, remove, contains: the three methods, each working on one bucket.

The main method runs the example, then adds 10008 so that it shares bucket 1 with key 1, removes 1, removes a key that was never added, and tries the smallest and largest keys, 0 and 1,000,000. Because main is in the same class, it can print a bucket directly.

Java
import java.util.LinkedList;

public class MyHashSet {

    private static final int SIZE = 10007;                // number of buckets, a prime

    @SuppressWarnings("unchecked")
    private final LinkedList<Integer>[] buckets = new LinkedList[SIZE];

    private static int index(int key) {
        return key % SIZE;                                // which bucket the key belongs in
    }

    public void add(int key) {
        int i = index(key);
        if (buckets[i] == null) {
            buckets[i] = new LinkedList<>();              // first key for this bucket
        }
        if (!buckets[i].contains(key)) {                  // a set holds each key once
            buckets[i].add(key);
        }
    }

    public void remove(int key) {
        LinkedList<Integer> bucket = buckets[index(key)];
        if (bucket != null) {
            bucket.remove(Integer.valueOf(key));          // remove the value, not an index
        }
    }

    public boolean contains(int key) {
        LinkedList<Integer> bucket = buckets[index(key)];
        return bucket != null && bucket.contains(key);
    }

    public static void main(String[] args) {
        MyHashSet set = new MyHashSet();
        set.add(1);
        set.add(2);
        System.out.println("contains(1): " + set.contains(1));
        System.out.println("contains(3): " + set.contains(3));
        set.add(2);                                       // already there
        System.out.println("contains(2): " + set.contains(2));
        set.remove(2);
        System.out.println("contains(2): " + set.contains(2));

        set.add(10008);                                   // 10008 % 10007 = 1, same bucket as 1
        System.out.println("bucket 1: " + set.buckets[1]);
        set.remove(1);
        System.out.println("after remove(1), bucket 1: " + set.buckets[1]
            + ", contains(10008): " + set.contains(10008));
        set.remove(5);                                    // never added
        set.add(0);
        set.add(1000000);
        System.out.println("contains(0): " + set.contains(0)
            + ", contains(1000000): " + set.contains(1000000)
            + ", contains(999999): " + set.contains(999999));
    }
}

Running it prints:

Output
contains(1): true
contains(3): false
contains(2): true
contains(2): false
bucket 1: [1, 10008]
after remove(1), bucket 1: [10008], contains(10008): true
contains(0): true, contains(1000000): true, contains(999999): false

The first four lines are the example: true, false, true, false. The fifth line is the collision from the picture, with 1 and 10008 sharing bucket 1. On the next line, remove(1) has left only 10008 in that bucket, and contains(10008) is still true, so removing one key does not disturb its neighbour. remove(5) printed nothing and threw nothing, because bucket 5 was never created. The last line shows that the smallest and largest keys, 0 and 1,000,000, both work, while 999,999 was never added.

Look closely at remove: it calls bucket.remove(Integer.valueOf(key)), not bucket.remove(key). LinkedList has two remove methods. remove(int index) deletes the element at a position, and remove(Object o) deletes an element equal to o. Given an int, Java picks the position version, so on a bucket holding only 10008, bucket.remove(10008) throws IndexOutOfBoundsException: Index: 10008, Size: 1. Integer.valueOf(key) turns the int into an Integer object, so the value version runs instead.

The original implementation, MyHashSet.java, is on GitHub.

Complexity

Each call computes one remainder and then works on a single bucket, so its cost depends on how many keys share that bucket.

  • Time: O(1) on average per call. With at most 10,000 keys spread over 10007 buckets, a bucket holds about one key, and each method walks only that short list. If many keys land in the same bucket, such as 1, 10008, 20015 and so on, a call walks all of them, which is O(n) in the worst case, where n is the number of keys stored.
  • Space: O(SIZE + n). The array always has 10007 slots, each bucket in use adds one LinkedList object, and each stored key adds one list node.

For the same structure with a value stored next to each key, see Design HashMap.