class HashTable { constructor(size) { this.size = size; this.table = new Array(size).fill(null); } hash(key) { return key % this.size; } insert(key) { let idx = this.hash(key); while (this.table[idx] !== null) { idx = (idx + 1) % this.size; } this.table[idx] = key; } } const ht = new HashTable(7); [10, 22, 31, 4, 15].forEach(k => ht.insert(k)); console.log(ht.table);
Keys are inserted using hash = key % 7. Collisions are resolved by moving to the next empty slot.
- 10 % 7 = 3 → slot 3 empty → insert 10
- 22 % 7 = 1 → slot 1 empty → insert 22
- 31 % 7 = 3 → slot 3 occupied → move to 4 → empty → insert 31
- 4 % 7 = 4 → slot 4 occupied → move to 5 → empty → insert 4
- 15 % 7 = 1 → slot 1 occupied → move to 2 → empty → insert 15
Final table: [null, 22, 15, 10, 31, 4, null]
Hash function: key % 5
- 42 % 5 = 2
- Index 2 has 22 (not 42), move to 3
- Index 3 has 32 (not 42), move to 4
- Index 4 has 42 → found
insert(key) {
let idx = this.hash(key);
while (this.table[idx] !== null) {
idx = (idx + 1) % this.size;
}
this.table[idx] = key;
}If the table is full, the while loop cycles through all indices endlessly because no null slot is found, causing an infinite loop.
class HashTable { constructor(size) { this.size = size; this.table = new Array(size).fill(null); } hash(key) { return key % this.size; } insert(key) { let idx = this.hash(key); while (this.table[idx] !== null && this.table[idx] !== 'DELETED') { idx = (idx + 1) % this.size; } this.table[idx] = key; } delete(key) { let idx = this.hash(key); let start = idx; while (this.table[idx] !== null) { if (this.table[idx] === key) { this.table[idx] = 'DELETED'; return true; } idx = (idx + 1) % this.size; if (idx === start) break; } return false; } } const ht = new HashTable(5); [12, 22, 32, 42].forEach(k => ht.insert(k)); ht.delete(22); ht.insert(52); console.log(ht.table);
Initial table after insertions: [42, null, 12, 22, 32]
Delete 22 sets index 3 to 'DELETED'.
Insert 52 hashes to 2, probes to 3 ('DELETED'), inserts 52 there.
Final table: [42, null, 12, 52, 32]
Linear probing places collided keys in the next available slot, creating groups of occupied slots. This makes future collisions near these groups cause longer searches, called primary clustering.
