The Wayback Machine - https://web.archive.org/web/20241117003223/https://www.geeksforgeeks.org/implementation-of-hash-table-in-c-using-separate-chaining/
Open In App

Implementation of Hash Table in C/C++ using Separate Chaining

Last Updated : 01 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Introduction:

Hashing is a technique that maps a large set of data to a small set of data. It uses a hash function for doing this mapping. It is an irreversible process and we cannot find the original value of the key from its hashed value because we are trying to map a large set of data into a small set of data, which may cause collisions. It is not uncommon to encounter collisions when mapping a large dataset into a smaller one. Suppose, We have three buckets and each bucket can store 1L of water in it and we have 5L of water also. We have to put all the water in these three buckets and this kind of situation is known as a collision. URL shorteners are an example of hashing as it maps large size URL to small size

Some Examples of Hash Functions:

  • key % number of buckets
  • ASCII value of character * PrimeNumberx. Where x = 1, 2, 3….n
  • You can make your own hash function but it should be a good hash function that gives less number of collisions.

Components of Hashing

Bucket Index:

The value returned by the Hash function is the bucket index for a key in a separate chaining method. Each index in the array is called a bucket as it is a bucket of a linked list.

Rehashing:

Rehashing is a concept that reduces collision when the elements are increased in the current hash table. It will make a new array of doubled size and copy the previous array elements to it and it is like the internal working of vector in C++. Obviously, the Hash function should be dynamic as it should reflect some changes when the capacity is increased. The hash function includes the capacity of the hash table in it, therefore, While copying key values from the previous array hash function gives different bucket indexes as it is dependent on the capacity (buckets) of the hash table. Generally,  When the value of the load factor is greater than 0.5 rehashings are done. 

  • Double the size of the array.
  • Copy the elements of the previous array to the new array. We use the hash function while copying each node to a new array again therefore, It will reduce collision.
  • Delete the previous array from the memory and point your hash map’s inside array pointer to this new array.
  • Generally, Load Factor = number of elements in Hash Map / total number of buckets (capacity).

Collision:

Collision is the situation when the bucket index is not empty. It means that a linked list head is present at that bucket index. We have two or more values that map to the same bucket index.

Major Functions in our Program

  • Insertion
  • Search
  • Hash Function
  • Delete
  • Rehashing

Hash Map

Implementation without Rehashing:

C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Linked List node
struct node {
 
    // key is string
    char* key;
 
    // value is also string
    char* value;
    struct node* next;
};
 
// like constructor
void setNode(struct node* node, char* key, char* value)
{
    node->key = key;
    node->value = value;
    node->next = NULL;
    return;
};
 
struct hashMap {
 
    // Current number of elements in hashMap
    // and capacity of hashMap
    int numOfElements, capacity;
 
    // hold base address array of linked list
    struct node** arr;
};
 
// like constructor
void initializeHashMap(struct hashMap* mp)
{
 
    // Default capacity in this case
    mp->capacity = 100;
    mp->numOfElements = 0;
 
    // array of size = 1
    mp->arr = (struct node**)malloc(sizeof(struct node*)
                                    * mp->capacity);
    return;
}
 
int hashFunction(struct hashMap* mp, char* key)
{
    int bucketIndex;
    int sum = 0, factor = 31;
    for (int i = 0; i < strlen(key); i++) {
 
        // sum = sum + (ascii value of
        // char * (primeNumber ^ x))...
        // where x = 1, 2, 3....n
        sum = ((sum % mp->capacity)
               + (((int)key[i]) * factor) % mp->capacity)
              % mp->capacity;
 
        // factor = factor * prime
        // number....(prime
        // number) ^ x
        factor = ((factor % __INT16_MAX__)
                  * (31 % __INT16_MAX__))
                 % __INT16_MAX__;
    }
 
    bucketIndex = sum;
    return bucketIndex;
}
 
void insert(struct hashMap* mp, char* key, char* value)
{
 
    // Getting bucket index for the given
    // key - value pair
    int bucketIndex = hashFunction(mp, key);
    struct node* newNode = (struct node*)malloc(
 
        // Creating a new node
        sizeof(struct node));
 
    // Setting value of node
    setNode(newNode, key, value);
 
    // Bucket index is empty....no collision
    if (mp->arr[bucketIndex] == NULL) {
        mp->arr[bucketIndex] = newNode;
    }
 
    // Collision
    else {
 
        // Adding newNode at the head of
        // linked list which is present
        // at bucket index....insertion at
        // head in linked list
        newNode->next = mp->arr[bucketIndex];
        mp->arr[bucketIndex] = newNode;
    }
    return;
}
 
void delete (struct hashMap* mp, char* key)
{
 
    // Getting bucket index for the
    // given key
    int bucketIndex = hashFunction(mp, key);
 
    struct node* prevNode = NULL;
 
    // Points to the head of
    // linked list present at
    // bucket index
    struct node* currNode = mp->arr[bucketIndex];
 
    while (currNode != NULL) {
 
        // Key is matched at delete this
        // node from linked list
        if (strcmp(key, currNode->key) == 0) {
 
            // Head node
            // deletion
            if (currNode == mp->arr[bucketIndex]) {
                mp->arr[bucketIndex] = currNode->next;
            }
 
            // Last node or middle node
            else {
                prevNode->next = currNode->next;
            }
            free(currNode);
            break;
        }
        prevNode = currNode;
        currNode = currNode->next;
    }
    return;
}
 
char* search(struct hashMap* mp, char* key)
{
 
    // Getting the bucket index
    // for the given key
    int bucketIndex = hashFunction(mp, key);
 
    // Head of the linked list
    // present at bucket index
    struct node* bucketHead = mp->arr[bucketIndex];
    while (bucketHead != NULL) {
 
        // Key is found in the hashMap
        if (bucketHead->key == key) {
            return bucketHead->value;
        }
        bucketHead = bucketHead->next;
    }
 
    // If no key found in the hashMap
    // equal to the given key
    char* errorMssg = (char*)malloc(sizeof(char) * 25);
    errorMssg = "Oops! No data found.\n";
    return errorMssg;
}
 
// Drivers code
int main()
{
 
    // Initialize the value of mp
    struct hashMap* mp
        = (struct hashMap*)malloc(sizeof(struct hashMap));
    initializeHashMap(mp);
 
    insert(mp, "Yogaholic", "Anjali");
    insert(mp, "pluto14", "Vartika");
    insert(mp, "elite_Programmer", "Manish");
    insert(mp, "GFG", "GeeksforGeeks");
    insert(mp, "decentBoy", "Mayank");
 
    printf("%s\n", search(mp, "elite_Programmer"));
    printf("%s\n", search(mp, "Yogaholic"));
    printf("%s\n", search(mp, "pluto14"));
    printf("%s\n", search(mp, "decentBoy"));
    printf("%s\n", search(mp, "GFG"));
 
    // Key is not inserted
    printf("%s\n", search(mp, "randomKey"));
 
    printf("\nAfter deletion : \n");
 
    // Deletion of key
    delete (mp, "decentBoy");
    printf("%s\n", search(mp, "decentBoy"));
 
    return 0;
}


C++




#include <iostream>
#include <cstring>
 
// Linked List node
struct node {
    // key is string
    char* key;
    // value is also string
    char* value;
    struct node* next;
};
 
// like constructor
void setNode(struct node* node, char* key, char* value) {
    node->key = key;
    node->value = value;
    node->next = NULL;
    return;
}
 
struct hashMap {
    // Current number of elements in hashMap
    // and capacity of hashMap
    int numOfElements, capacity;
    // hold base address array of linked list
    struct node** arr;
};
 
// like constructor
void initializeHashMap(struct hashMap* mp) {
    // Default capacity in this case
    mp->capacity = 100;
    mp->numOfElements = 0;
    // array of size = 1
    mp->arr = (struct node**)malloc(sizeof(struct node*) * mp->capacity);
    return;
}
 
int hashFunction(struct hashMap* mp, char* key) {
    int bucketIndex;
    int sum = 0, factor = 31;
    for (int i = 0; i < strlen(key); i++) {
        // sum = sum + (ascii value of
        // char * (primeNumber ^ x))...
        // where x = 1, 2, 3....n
        sum = ((sum % mp->capacity) + (((int)key[i]) * factor) % mp->capacity) % mp->capacity;
        // factor = factor * prime
        // number....(prime
        // number) ^ x
        factor = ((factor % __INT16_MAX__) * (31 % __INT16_MAX__)) % __INT16_MAX__;
    }
    bucketIndex = sum;
    return bucketIndex;
}
 
void insert(struct hashMap* mp, char* key, char* value) {
    // Getting bucket index for the given
    // key - value pair
    int bucketIndex = hashFunction(mp, key);
    struct node* newNode = (struct node*)malloc(
        // Creating a new node
        sizeof(struct node));
    // Setting value of node
    setNode(newNode, key, value);
    // Bucket index is empty....no collision
    if (mp->arr[bucketIndex] == NULL) {
        mp->arr[bucketIndex] = newNode;
    }
    // Collision
    else {
        // Adding newNode at the head of
        // linked list which is present
        // at bucket index....insertion at
        // head in linked list
        newNode->next = mp->arr[bucketIndex];
        mp->arr[bucketIndex] = newNode;
    }
    return;
}
 
void deleteKey(struct hashMap* mp, char* key) {
    // Getting bucket index for the
    // given key
    int bucketIndex = hashFunction(mp, key);
    struct node* prevNode = NULL;
    // Points to the head of
    // linked list present at
    // bucket index
    struct node* currNode = mp->arr[bucketIndex];
    while (currNode != NULL) {
        // Key is matched at delete this
        // node from linked list
        if (strcmp(key, currNode->key) == 0) {
            // Head node
            // deletion
            if (currNode == mp->arr[bucketIndex]) {
                mp->arr[bucketIndex] = currNode->next;
            }
            // Last node or middle node
            else {
                prevNode->next = currNode->next;
}
free(currNode);
break;
}
 
prevNode = currNode;
        currNode = currNode->next;
    }
return;
}
 
char* search(struct hashMap* mp, char* key) {
// Getting the bucket index for the given key
int bucketIndex = hashFunction(mp, key);
// Head of the linked list present at bucket index
struct node* bucketHead = mp->arr[bucketIndex];
 
while (bucketHead != NULL) {
     
    // Key is found in the hashMap
    if (strcmp(bucketHead->key, key) == 0) {
        return bucketHead->value;
    }
     
    bucketHead = bucketHead->next;
}
 
// If no key found in the hashMap equal to the given key
char* errorMssg = (char*)malloc(sizeof(char) * 25);
strcpy(errorMssg, "Oops! No data found.\n");
return errorMssg;
}
 
 
// Drivers code
int main()
{
// Initialize the value of mp
struct hashMap* mp = (struct hashMap*)malloc(sizeof(struct hashMap));
initializeHashMap(mp);
insert(mp, "Yogaholic", "Anjali");
insert(mp, "pluto14", "Vartika");
insert(mp, "elite_Programmer", "Manish");
insert(mp, "GFG", "GeeksforGeeks");
insert(mp, "decentBoy", "Mayank");
 
printf("%s\n", search(mp, "elite_Programmer"));
printf("%s\n", search(mp, "Yogaholic"));
printf("%s\n", search(mp, "pluto14"));
printf("%s\n", search(mp, "decentBoy"));
printf("%s\n", search(mp, "GFG"));
 
// Key is not inserted
printf("%s\n", search(mp, "randomKey"));
 
printf("\nAfter deletion : \n");
 
// Deletion of key
deleteKey(mp, "decentBoy");
 
// Searching the deleted key
printf("%s\n", search(mp, "decentBoy"));
return 0;
}


Output

Manish
Anjali
Vartika
Mayank
GeeksforGeeks
Oops! No data found.


After deletion : 
Oops! No data found.

Explanation:

  • insertion: Inserts the key-value pair at the head of a linked list which is present at the given bucket index.
  • hashFunction: Gives the bucket index for the given key. Our hash function = ASCII value of character * primeNumberx. The prime number in our case is 31 and the value of x is increasing from 1 to n for consecutive characters in a key.
  • deletion: Deletes key-value pair from the hash table for the given key. It deletes the node from the linked list which holds the key-value pair.
  • Search: Search for the value of the given key. 
  • This implementation does not use the rehashing concept. It is a fixed-sized array of linked lists.
  • Key and value both are strings in the given example.

Time Complexity and Space Complexity:

The time complexity of hash table insertion and deletion operations is O(1) on average. There is some mathematical calculation that proves it.

  • Time Complexity of Insertion: In the average case it is constant. In the worst case, it is linear.
  • Time Complexity of Search: In the average case it is constant. In the worst case, it is linear.
  • Time Complexity of Deletion: In average cases it is constant. In the worst case, it is linear.
  • Space Complexity: O(n) as it has n number of elements.

Related Articles:



Similar Reads

Implementation of Hash Table in Python using Separate Chaining
A hash table is a data structure that allows for quick insertion, deletion, and retrieval of data. It works by using a hash function to map a key to an index in an array. In this article, we will implement a hash table in Python using separate chaining to handle collisions. Separate chaining is a technique used to handle collisions in a hash table.
7 min read
Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone mus
10 min read
Separate Chaining Collision Handling Technique in Hashing
Separate Chaining is a collision handling technique. Separate chaining is one of the most popular and commonly used techniques in order to handle collisions. In this article, we will discuss about what is Separate Chain collision handling technique, its advantages, disadvantages, etc. What is Collision? Since a hash function gets us a small number
4 min read
What are Hash Functions and How to choose a good Hash Function?
Prerequisite: Hashing | Set 1 (Introduction) What is a Hash Function? A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. W
5 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Implementation of Dynamic Segment Trees with Poly Hash Tables
Dynamic Segment Trees with Poly Hash Tables is a data structure that combines the benefits of both dynamic segment trees and hash tables to efficiently handle range queries on an array of elements. To understand this topic, let's start with an example. Consider an array of N elements {1, 2, 3, ..., N}. We want to support two operations on this arra
15+ min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Various load balancing techniques used in Hash table to ensure efficient access time
Load balancing refers to the process of distributing workloads evenly across multiple servers, nodes, or other resources to ensure optimal resource utilization, maximize output, minimize response time, and avoid overload of any single resource. Load balancing helps to improve the reliability and scalability of applications and systems, as well as r
3 min read
Hash Table vs Trie
What is Hash Table? An array that stores pointers to records corresponding to a given element. An entry in the hash table is NIL if no existing element has a hash function value equal to the index for the entry. In simple terms, we can say that a hash table is a generalization of the array. Hash table gives the functionality in which a collection o
5 min read
Hash Table vs STL Map
This article focus on : Compare and contrast Hash table and an STL Map. How is the hash table implemented? If the number of inputs is small, which data structure options can be used instead of a hash table? Hash table In a hash table, a value is stored by calling a hash function on a key. Values are not stored in sorted order.Additionally, since ha
4 min read
Why use an Array to implement a "list" instead of a Hash Table?
What is an Array?An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. C/C++ Code #include <iostream> using namespace std; // driver program int main() { // initaizling array int arr[] = {1, 2,
4 min read
Implementing own Hash Table with Open Addressing Linear Probing
Prerequisite - Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in JavaIn Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed). Insert(k) - Keep probing u
13 min read
Advantages of BST over Hash Table
Hash Table supports following operations in O(1) time. 1) Search 2) Insert 3) Delete The time complexity of above operations in a self-balancing Binary Search Tree (BST) (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(Logn). So Hash Table seems to beating BST in all common operations. When should we prefer BST over Hash Tables, what are advan
2 min read
Hash Table Data Structure
What is Hash Table?A Hash table is defined as a data structure used to insert, look up, and remove key-value pairs quickly. It operates on the hashing concept, 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 th
11 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
Hashtables Chaining with Doubly Linked Lists
Prerequisite - Hashing Introduction, Hashtable using Singly Linked List & Implementing our Own Hash Table with Separate Chaining in Java Implementing hash table using Chaining through Doubly Linked List is similar to implementing Hashtable using Singly Linked List. The only difference is that every node of Linked List has the address of both, t
12 min read
Method Chaining In Java with Examples
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.). Method chaining in Java is a common syntax to invoke multiple methods c
3 min read
Dividing a Large file into Separate Modules in C/C++, Java and Python
If you ever wanted to write a large program or software, the most common rookie mistake is to jump in directly and try to write all the necessary code into a single program and later try to debug or extend later. This kind of approach is doomed to fail and would usually require re-writing from scratch. So in order to tackle this scenario, we can tr
14 min read
Segregate 1s and 0s in separate halves of a Binary String
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required. Examples: Input: str = "01011100"Output: 2Explanation: The operations performed are as follows: "01011100" -> "11101000"
5 min read
Minimize cost to reach bottom right from top left corner of Matrix with given separate cost for each move
Given an integer N and three N x N matrices X[][], Y[][], and Z[][], the task is to calculate the minimum cost required to reach the bottom right from the top left of the matrix using the following moves: Move to a cell in the right direction from (i, j) which will cost X[i][j].Move to a cell in the downward direction from (i, j) which will cost Y[
15+ min read
Sorting using trivial hash function
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 10^6). Examples: Input : 9 4 3 5 8 Output : 3 4 5 8
15+ min read
Classify strings from an array using Custom Hash Function
Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string. Examples: Input: arr[][] = {"geeks", "for", "geeks"}Output:geeks geeksforExplanation:The hash value of string "for" is (102 + 111 + 114) % 26 = 14The hash va
8 min read
Find the Longest Common Substring using Binary search and Rolling Hash
Given two strings X and Y, the task is to find the length of the longest common substring. Examples: Input: X = “GeeksforGeeks”, y = “GeeksQuiz” Output: 5 Explanation: The longest common substring is “Geeks” and is of length 5. Input: X = “abcdxyz”, y = “xyzabcd” Output: 4 Explanation: The longest common substring is “abcd” and is of length 4. Inpu
11 min read
Sort elements by frequency | Set 4 (Efficient approach using hash)
Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first. Examples: Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8} Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6} Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8} Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999} Recommended: Pl
12 min read
Trie memory optimization using hash map
We introduced and discussed an implementation in below post. Trie | (Insert and Search) - GeeksforGeeks The implementation used in above post uses an array of alphabet size with every node. It can be made memory efficient. One way to implementing Trie is linked set of nodes, where each node contains an array of child pointers, one for each symbol i
7 min read
Graph representations using set and hash
We have introduced Graph implementation using array of vectors in Graph implementation using STL for competitive programming | Set 1. In this post, a different implementation is used which can be used to implement graphs using sets. The implementation is for adjacency list representation of graph. A set is different from a vector in two ways: it st
15+ min read
Deletion in Hash Tables using Python
Hash tables are fundamental data structures used in computer science for efficient data storage and retrieval. They provide constant-time average-case complexity for basic operations like insertion, deletion, and search. Deletion in hash tables involves removing an element from the table based on its key. Python offers built-in support for hash tab
2 min read
Longest subsequence with adjacent difference as either 0 or 1 (Using Hash Map)
Given an array of n integers. The problem is to find maximum length of the subsequence with difference between adjacent elements as either 0 or 1.Examples: Input : arr[] = {2, 5, 6, 3, 7, 6, 5, 8}Output : 5The subsequence is {5, 6, 7, 6, 5}. Input : arr[] = {-2, -1, 5, -1, 4, 0, 3}Output : 4The subsequence is {-2, -1, -1, 0}. We have discussed a O(
8 min read
Multiplication table till N rows where every Kth row is table of K upto Kth term
Given a number N, the task is to print N rows where every Kth row consists of the multiplication table of K up to Kth term. Examples: Input: N = 3 Output: 1 2 4 3 6 9 Explanation: In the above series, in every Kth row, multiplication table of K upto K terms is printed. Input: N = 5 Output: 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 Approach: The idea is t
5 min read
Practice Tags :
three90RightbarBannerImg