KatInterview

816. Design HashSet

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core task is to design a HashSet data structure from scratch, without relying on any built-in hash table libraries. This involves implementing three main operations: add(key), remove(key), and contains(key). The challenge lies in creating an efficient system for storing and retrieving keys, which typically involves a hashing function to map keys to storage locations and a strategy to handle collisions (when multiple keys map to the same location).

Solution

Design HashSet in Python

class MyHashSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        # A prime number is often chosen for the size to help distribute keys uniformly.
        self.size = 769
        self.buckets = [[] for _ in range(self.size)]

    def _hash(self, key: int) -> int:
        """Hash function to map a key to a bucket index."""
        return key % self.size

    def add(self, key: int) -> None:
        index = self._hash(key)
        bucket = self.buckets[index]
        # Check if the key already exists to avoid duplicates.
        if key not in bucket:
            bucket.append(key)

    def remove(self, key: int) -> None:
        index = self._hash(key)
        bucket = self.buckets[index]
        # Using try-except to handle cases where the key does not exist,
        # as list.remove() raises a ValueError if the item is not found.
        try:
            bucket.remove(key)
        except ValueError:
            pass # Key not in the list, do nothing as per problem statement.

    def contains(self, key: int) -> bool:
        """
        Returns true if this set contains the specified element
        """
        index = self._hash(key)
        bucket = self.buckets[index]
        # 'in' operator performs a linear search on the list.
        return key in bucket


# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)

Design HashSet in Java

import java.util.LinkedList;
import java.util.List;

class MyHashSet {
    private final int BUCKET_SIZE;
    private List<Integer>[] buckets;

    /** Initialize your data structure here. */
    public MyHashSet() {
        // A prime number is often chosen for the size to help distribute keys uniformly.
        this.BUCKET_SIZE = 769;
        this.buckets = new LinkedList[BUCKET_SIZE];
        for (int i = 0; i < BUCKET_SIZE; i++) {
            buckets[i] = new LinkedList<>();
        }
    }
    
    // Hash function to map a key to a bucket index.
    private int hash(int key) {
        return key % BUCKET_SIZE;
    }
    
    public void add(int key) {
        int index = hash(key);
        List<Integer> bucket = buckets[index];
        // Check if the key already exists to avoid duplicates.
        if (!bucket.contains(key)) {
            bucket.add(key);
        }
    }
    
    public void remove(int key) {
        int index = hash(key);
        List<Integer> bucket = buckets[index];
        // Note: bucket.remove(key) would try to remove by index if key is an int.
        // We must use Integer.valueOf(key) to specify removal by object.
        bucket.remove(Integer.valueOf(key));
    }
    
    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        int index = hash(key);
        List<Integer> bucket = buckets[index];
        return bucket.contains(key);
    }
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet obj = new MyHashSet();
 * obj.add(key);
 * obj.remove(key);
 * boolean param_3 = obj.contains(key);
 */

Design HashSet in C++

class MyHashSet {
private:
    std::vector<std::list<int>> buckets;
    int size;

    // Hash function to map a key to a bucket index.
    int hash(int key) {
        return key % size;
    }

public:
    MyHashSet() {
        // A prime number is often chosen for the size to help distribute keys uniformly.
        size = 769;
        buckets.resize(size);
    }
    
    void add(int key) {
        int index = hash(key);
        // Search for the key in the bucket's list. std::find could also be used.
        for (int k : buckets[index]) {
            if (k == key) {
                return; // Key already exists, do nothing.
            }
        }
        // If not found, add it to the list.
        buckets[index].push_back(key);
    }
    
    void remove(int key) {
        int index = hash(key);
        // The remove method of std::list is convenient.
        // It erases all elements in the list that are equal to the given value.
        buckets[index].remove(key);
    }
    
    bool contains(int key) {
        int index = hash(key);
        // Search for the key in the bucket's list.
        for (int k : buckets[index]) {
            if (k == key) {
                return true; // Key found.
            }
        }
        return false; // Key not found.
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */

Design HashSet in TypeScript

class MyHashSet {
    private size: number;
    private buckets: number[][];

    constructor() {
        // A prime number is often chosen for the size to help distribute keys uniformly.
        this.size = 769;
        // Initialize an array of arrays (our buckets).
        this.buckets = Array.from({ length: this.size }, () => []);
    }

    // Hash function to map a key to a bucket index.
    private hash(key: number): number {
        return key % this.size;
    }

    add(key: number): void {
        const index = this.hash(key);
        const bucket = this.buckets[index];
        // Check if the key already exists to avoid duplicates.
        if (!bucket.includes(key)) {
            bucket.push(key);
        }
    }

    remove(key: number): void {
        const index = this.hash(key);
        const bucket = this.buckets[index];
        const keyIndexInBucket = bucket.indexOf(key);
        // If key exists in the bucket, remove it using splice.
        if (keyIndexInBucket !== -1) {
            bucket.splice(keyIndexInBucket, 1);
        }
    }

    contains(key: number): boolean {
        const index = this.hash(key);
        const bucket = this.buckets[index];
        // Array.prototype.includes() performs a linear search.
        return bucket.includes(key);
    }
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * var obj = new MyHashSet()
 * obj.add(key)
 * obj.remove(key)
 * var param_3 = obj.contains(key)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.