Sobes.tech
Junior — Middle

Can you give examples of collision resolution methods when working with hash tables?

sobes.tech AI

Answer from AI

Hash collisions occur when different keys hash to the same cell in a hash table. The main methods to resolve collisions are:

  1. Chaining method — each cell in the hash table stores a linked list of elements that have hashed to that cell. When a collision occurs, the new element is added to the list.

  2. Open addressing — upon collision, the next free cell is sought according to a specific rule (linear probing, quadratic probing, double hashing).

Example of chaining method:

class HashTable {
    var buckets: [[(key: String, value: Int)]]
    
    init(size: Int) {
        buckets = Array(repeating: [], count: size)
    }
    
    func hash(_ key: String) -> Int {
        return abs(key.hashValue) % buckets.count
    }
    
    func insert(key: String, value: Int) {
        let index = hash(key)
        buckets[index].append((key, value))
    }
}

Thus, the choice of method depends on performance and memory requirements.

Can you give examples of collision resolution methods… - sobes.tech