Junior — Middle
Explain the concept of a hash table and how it is used for storing data
sobes.tech AI
Answer from AI
A hash table is a data structure that allows efficient storage and quick retrieval of key-value pairs. It uses a hash function to convert the key into an array index where the corresponding value is stored.
Main principles:
- The hash function converts the key into a number (index).
- Values are stored in an array at this index.
- In case of collisions (when different keys produce the same index), resolution methods such as chaining (linked lists) or open addressing are used.
In C#, the Dictionary<TKey, TValue> class is often used to store data, which implements a hash table under the hood.
Example of usage:
var dict = new Dictionary<string, int>();
dict["apple"] = 5;
dict["banana"] = 3;
Console.WriteLine(dict["apple"]); // Outputs 5
Hash tables provide fast access to data — insertion, search, and deletion operations are usually performed in amortized O(1) time.