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 MyHashSetHashSetHashMapadd(key)remove(key)contains(key)
Example
contains(1) returns true
contains(3) returns false
add(2)
contains(2) returns true
remove(2)
contains(2) returns false
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)add(2)contains(1)contains(3)add(2)remove(2)contains(2)
The plainest way to keep the keys is one list, and that handles the example. But containscontains
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 % 10007addcontains
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)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]true
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>java.util
A bucket's list is created only when its first key arrives. Until then its slot in the array is null
What each method does
Every method starts by computing the bucket. addadd(2)removecontainsremovecontainsnull
Java Solution
The class has these parts:
: the number of buckets, 10007.SIZE : the array of buckets. Each slot is abuckets , orLinkedList<Integer> until its first key arrives.null : the hash function,index(key) , which picks the bucket.key % SIZE ,add ,remove : the three methods, each working on one bucket.contains
The mainmain
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:
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)contains(10008)remove(5)
Look closely at removebucket.remove(Integer.valueOf(key))bucket.remove(key)LinkedListremoveremove(int index)remove(Object o)ointbucket.remove(10008)IndexOutOfBoundsException: Index: 10008, Size: 1Integer.valueOf(key)intInteger
The original implementation,
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
object, and each stored key adds one list node.LinkedList
For the same structure with a value stored next to each key, see