↓Skip to main content
  1. LeetCode/

LeetCode 705: Design HashSet

·2 mins· ·
LeetCode Easy Array Hash-Table Linked-List Design
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-31

  • Submissions: Runtime Error ×2 → Accepted

Approach
#

The problem asks you to build it without the built-in set. The most basic hash table (Hash Table; Linked List, Others):

  • Allocate a fixed number of buckets (a prime such as 1009 spreads keys more evenly).
  • key % bucket_count chooses the bucket.
  • Different keys may share a bucket (a collision), so each bucket is a list searched on every operation.

My Attempts
#

I originally just wrapped the built-in set: attempt 1’s remove called itself (infinite recursion); attempt 2 used set.remove, raising KeyError for a missing key; attempt 3 switched to discard and passed. Here it is a real implementation.

Solution
#

class MyHashSet:
    def __init__(self):
        self.size = 1009
        self.buckets = [[] for _ in range(self.size)]

    def add(self, key: int) -> None:
        b = self.buckets[key % self.size]
        if key not in b:
            b.append(key)

    def remove(self, key: int) -> None:
        b = self.buckets[key % self.size]
        if key in b:
            b.remove(key)

    def contains(self, key: int) -> bool:
        return key in self.buckets[key % self.size]

Complexity
#

Each operation averages O(n / buckets), space O(buckets + n).

Mistakes to Avoid
#

  • Removing a missing key must not raise.
  • A prime bucket count keeps keys from clustering in a few buckets.

Interview Explanation
#

I allocate a fixed number of buckets, place each key by its remainder, and use a list per bucket for collisions, checking membership before adding or removing. Each operation averages O(n / buckets).

Related

LeetCode 697: Degree of an Array
·2 mins
LeetCode Easy Array Hash-Table
LeetCode 697 note: record each value’s count, first index and last index; among the most frequent values, take the shortest span
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 599: Minimum Index Sum of Two Lists
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 599 note: map list1’s strings to indices, sum both indices while scanning list2, and keep every string with the minimum sum
LeetCode 575: Distribute Candies
·1 min
LeetCode Easy Array Hash-Table
LeetCode 575 note: at most n / 2 candies can be eaten and at most len(set) kinds exist; the answer is the smaller of the two
LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0