Junior — Middle
Can you explain the principle of how a hash table works and how quick data access is achieved?
sobes.tech AI
Answer from AI
A hash table is a data structure that provides fast access to elements by key.
How it works:
- The key is transformed into an array index using a hash function — a numerical value that determines the position in the array.
- The value or a list of values (in case of collisions) is stored at this index.
- When searching for a key, the hash function calculates the index, and the desired element is quickly found at that position.
Fast access is achieved because calculating the index and accessing the array element are operations with constant time complexity (O(1)).
Collisions (when different keys produce the same index) are handled using various methods, such as chaining (linked lists) or open addressing.
Example in C# using Dictionary<TKey, TValue>:
var dict = new Dictionary<string, int>();
dict["apple"] = 5;
dict["banana"] = 3;
int value = dict["apple"]; // Fast access by key "apple"
Inside Dictionary, a hash table is used to ensure high performance of add and search operations.