Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet
class:
class MyHashSet {
public MyHashSet();
public void add(int key);
public void remove(int key);
public boolean contains(int key);
}
To implement a HashSet, we need to focus on three primary functionalities:
Given the constraints (e.g., value ranges), one simple and efficient way is to use a boolean array where the index represents the element.
i
in the array will represent the presence of the key i
.Here’s how the implementation looks:
public class MyHashSet {
private boolean[] set;
public MyHashSet() {
set = new boolean[1000001]; // Initializes the array to cover keys from 0 to 1,000,000
}
public void add(int key) {
set[key] = true;
}
public void remove(int key) {
set[key] = false;
}
public boolean contains(int key) {
return set[key];
}
}
add
):
remove
):
contains
):
Thus, the solution provides O(1) time complexity for all operations, making it very efficient.
However, this solution uses extra space proportional to the range of keys we support (from 0 to 1,000,000), making its space complexity O(n), where n is the range of possible key values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?