Hash Tables

A Hash Table is a data structure used to insert, look up, and remove key-value pairs quickly. It operates on the concept of hashing, where each key is translated by a hash function into a distinct index in an array. The index functions as a storage location for the matching value. In simple words, it maps the keys with the values. It provides direct access to its items in constant time and ensures that for each key, data occurs at most once. Dictionaries and maps in programming languages which is generally used in caching systems for faster data retrieval and database indexing for quick lookups.

Example

// Initialize a regular dictionary
var dict = new Dictionary<string, int>()
            {
                {"apple", 1},
                {"banana", 2},
                {"cherry", 3}
            };

Operations of the Hash Table in data structure

There are some operations of the Hash Table in the data structure:

  • Access: Accessing an element in a hash table is done using the key. The key is processed through the hash function to generate the index where the corresponding value can be found.

  • Insertion: This operation involves inserting a new key-value pair into the hash table. The key is processed through a hash function to generate an index where the corresponding value is stored.

  • Deletion: This operation involves removing a key-value pair from the hash table. Similar to the search operation, the key is processed through the hash function to find the index where the corresponding value is stored, and then the key-value pair is removed from that index.

  • Search: This operation involves searching for a key-value pair in the hash table. The key is processed through the same hash function to generate the index where the corresponding value can be found.

  • Update: Updating a value in a hash table is similar to the access operation. The key is used to find the corresponding value in the hash table. Once the value is found, it can be updated with the new value.

  • Sort: N/A.

Complexity Table

OperationBest CaseAverage CaseWorst Case

Insertion

O(1)

O(1)

O(N)

Search

O(1)

O(1)

O(N)

Deletion

O(1)

O(1)

O(N)

Update

O(1)

O(1)

O(N)

Hash Collision

In computer science, a hash collision occurs when two distinct pieces of data in a hash table share the same hash value. This happens when a hash function, which takes a data input and returns a fixed length of bits, maps different data to the same hash. There are strategies to handle them, like chaining (linked lists) or open addressing.

Last updated