Design HashSet — LeetCode 705 Python Solution

EasyDesignArrayHash TableLinked ListHash Function
Problem
#705
Reading time
4 min

The problem

Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet.

Example

Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
Output
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();

Python solution

Python
class MyHashSet:
    def __init__(self):
        self.data = [False] * 1000001

    def add(self, key: int) -> None:
        self.data[key] = True

    def remove(self, key: int) -> None:
        self.data[key] = False

    def contains(self, key: int) -> bool:
        return self.data[key]


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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 705. Design HashSet is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 705. Design HashSet?
LeetCode 705. Design HashSet is rated Easy on LeetCode.
What is the time complexity of LeetCode 705. Design HashSet?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 705. Design HashSet?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 705. Design HashSet cover?
LeetCode 705. Design HashSet is tagged Design, Array, Hash Table, Linked List and Hash Function on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview