Design HashSet Visualizer & Step-by-Step Algorithm Solution

Design a HashSet without using any built-in hash table libraries, demonstrating hashing (key % size) and collision resolution via separate chaining in dynamic buckets.

Category: arrays | Difficulty: Easy

Tags: HashSet, Hashing, Separate Chaining, Collision Resolution, Buckets

Design HashSet

Hash Buckets Array (modulo 7)
[]
0
[]
1
[]
2
[]
3
[]
4
[]
5
[]
6
HASH SET
(Empty Set)
100%
state
bucket count (size)7
total keys0
operationnew MyHashSet()
Initialization
1/18
Explanation

Initialize MyHashSet with 7 empty bucket chains for separate chaining.

Source Code
1class MyHashSet {
2 private size = 7;
3 private buckets: number[][] = Array.from({ length: 7 }, () => []);
4
5 private hash(key: number): number {
6 return key % this.size;
7 }
8
9 add(key: number): void {
10 const index = this.hash(key);
11 const bucket = this.buckets[index];
12 if (!bucket.includes(key)) {
13 bucket.push(key);
14 }
15 }
16
17 remove(key: number): void {
18 const index = this.hash(key);
19 const bucket = this.buckets[index];
20 const i = bucket.indexOf(key);
21 if (i !== -1) {
22 bucket.splice(i, 1);
23 }
24 }
25
26 contains(key: number): boolean {
27 const index = this.hash(key);
28 const bucket = this.buckets[index];
29 return bucket.includes(key);
30 }
31}