Junior — Middle
Explain what a hash table data structure is and how it works
sobes.tech AI
Answer from AI
A hash table is a data structure that stores key-value pairs and provides very fast access to data by key. It works using a hash function that transforms the key into an array index where the value is stored.
Working principle:
- When adding a key-value pair, the key is processed through the hash function, which returns an index.
- The value is stored in the array at this index.
- When searching for a key, the hash function again calculates the index, and the value is quickly retrieved.
To avoid collisions (when different keys produce the same index), methods such as:
- chaining (storing multiple elements in one cell as a list)
- open addressing (searching for the next free cell)
In C#, an example of using a dictionary (Dictionary), which is implemented based on a hash table:
var dict = new Dictionary<string, int>();
dict["apple"] = 5;
int value = dict["apple"]; // value == 5
Hash tables provide an average complexity of O(1) for insert, delete, and search operations.