Visualize Hash Table operations (Insert, Search, Delete) and collision resolution strategies.
Create a hash table to begin.
A hash table is a data structure that maps keys to values for highly efficient lookups. It uses a hash function to compute an index (or "hash code") into an array of buckets or slots, from which the desired value can be found.
index = hashCode % arraySize
).
class HashTableChaining {
constructor(size) {
this.table = new Array(size).fill(null).map(() => []); // Array of arrays (acting as lists)
this.size = size;
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * (i + 1)) % this.size;
}
return hash;
}
insert(key, value) {
const index = this._hash(key);
const bucket = this.table[index];
// Check if key already exists in the bucket's chain
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket[i][1] = value; // Update existing key
return;
}
}
// Key not found, add new entry
bucket.push([key, value]);
}
search(key) {
const index = this._hash(key);
const bucket = this.table[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
return bucket[i][1]; // Return value
}
}
return undefined; // Key not found
}
delete(key) {
const index = this._hash(key);
const bucket = this.table[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket.splice(i, 1); // Remove entry
return true;
}
}
return false; // Key not found
}
}