Junior — Middle
How does the system handle the situation when two elements have the same hash key in a hash table?
sobes.tech AI
Answer from AI
When two elements in a hash table have the same hash key (collision), collision resolution methods are applied. Main approaches:
- Chaining — each hash table bucket contains a linked list (or other container) of all elements with the same hash. New elements are added to this list.
- Open addressing — upon collision, the next free slot is searched according to a probing sequence (linear, quadratic, or double hashing).
Example of chaining in C++:
std::unordered_map<int, std::string> map;
map[42] = "Answer";
map[42] = "New Answer"; // overwrites previous value for key 42
unordered_map uses chaining internally to handle collisions. During search, elements in the chain are checked.
Thus, the system ensures correct storage and retrieval even with collisions.