EasyNeetCode150ArrayHash TableDesignLinked ListHash Function

Design Hashset

Implement hash set.

Examples

Input
HashSet operations: add(1), contains(1)=true, remove(1), contains(1)=false
Output
true,null,false

Basic operations.

Constraints

  • 1 <= key <= 10^6
  • At most 10^4 calls

Approaches

Direct addressing.

CodeT: O(1) all | S: O(M) array size M=max key

Hash + linked list.

CodeT: O(1) avg | S: O(M+N) storage

Probe for slots.

CodeT: O(1) amortized | S: O(M)

Complexity Comparison

Boolean Array
T: O(1) allS: O(M) array size M=max key

Direct addressing.

Chaining
T: O(1) avgS: O(M+N) storage

Hash + linked list.

Open Addressing
T: O(1) amortizedS: O(M)

Probe for slots.

Common Mistakes

Not handling collisions

Wrong hash function

Not resizing

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler