Middle
What collision resolution methods are you familiar with?
sobes.tech AI
Answer from AI
-
Open addressing: when a collision occurs, an alternative free position in the table is sought using various strategies:
- Linear probing: sequentially probing cells with a constant step.
// Example of linear probing func (ht *HashTable) get(key int) (int, bool) { index := ht.hash(key) for i := 0; i < ht.size; i++ { probeIndex := (index + i) % ht.size if ht.table[probeIndex].key == key && ht.table[probeIndex].occupied { return ht.table[probeIndex].value, true } if !ht.table[probeIndex].occupied && ht.table[probeIndex].value == 0 /* assuming 0 means empty */ { return 0, false // Not found } } return 0, false // Table is full }- Quadratic probing: probing cells with an increasing quadratic step ($i^2$).
- Double hashing: using a second hash function to determine the probing step.
-
Separate chaining: each hash table cell contains a pointer to a linked list (or another data structure), where elements with the same hash are added.
type Node struct {
key int
value int
next *Node
}
type HashTableChain struct {
table []*Node
size int
}
func (ht *HashTableChain) get(key int) (int, bool) {
index := ht.hash(key)
currentNode := ht.table[index]
for currentNode != nil {
if currentNode.key == key {
return currentNode.value, true
}
currentNode = currentNode.next
}
return 0, false
}
- Cuckoo hashing: using two or more hash functions. When inserting an element, it is placed in the first free cell determined by one of the hash functions. If both cells are occupied, one of the existing elements is "pushed out" to an alternative location determined by its second hash function.
Comparison of methods:
| Method | Advantages | Disadvantages |
|---|---|---|
| Open addressing | Memory saving (no pointers), better local storage | Sensitivity to load factor, clustering problem |
| Separate chaining | Less sensitivity to load factor, implementation simplicity | Additional memory overhead for pointers, potentially lower cache hits |
| Cuckoo hashing | Guaranteed average search time O(1) | More complex implementation, potential cycle issues during insertion |