Bird
0
0
DSA Cprogramming~30 mins

HashMap Implementation from Scratch in DSA C - Build from Scratch

Choose your learning style9 modes available
HashMap Implementation from Scratch
📖 Scenario: Imagine you are building a simple phone book application. You want to store names and their phone numbers so you can quickly find a number by a name. To do this efficiently, you will create your own HashMap from scratch in C.
🎯 Goal: Build a basic HashMap in C that can store key-value pairs (names and phone numbers), handle collisions using chaining, and allow insertion and lookup operations.
📋 What You'll Learn
Create a struct for HashMap entries with key and value
Create a HashMap struct with an array of pointers for buckets
Implement a simple hash function for strings
Implement insert and search functions
Handle collisions using linked lists (chaining)
Print the phone number for a given name
💡 Why This Matters
🌍 Real World
HashMaps are used in many applications like phone books, caches, and databases to quickly find data by keys.
💼 Career
Understanding how HashMaps work internally helps in optimizing software and solving problems efficiently in software development roles.
Progress0 / 4 steps
1
Create the basic data structures
Create a struct called Entry with char key[50], char value[15], and a pointer next to another Entry. Then create a struct called HashMap with an array buckets of size 10 holding pointers to Entry.
DSA C
Hint

Think of Entry as a node in a linked list holding a name and phone number. The HashMap holds an array of these lists.

2
Add a hash function and initialize the HashMap
Add a function int hash(char* key) that returns the sum of ASCII values of characters in key modulo 10. Also, write a function void initHashMap(HashMap* map) that sets all buckets pointers to NULL.
DSA C
Hint

The hash function converts a string to an index between 0 and 9. Initializing sets all bucket pointers to NULL.

3
Implement insert and search functions
Write a function void insert(HashMap* map, char* key, char* value) that adds a new Entry to the correct bucket using chaining. Also write char* search(HashMap* map, char* key) that returns the value for the given key or NULL if not found.
DSA C
Hint

Insert adds new entries at the start of the linked list for the bucket. Search walks through the list to find the key.

4
Test the HashMap by inserting and searching
In main(), create a HashMap variable called phoneBook. Initialize it using initHashMap. Insert these entries: ("Alice", "12345"), ("Bob", "67890"), ("Charlie", "54321"). Then print the phone number for "Bob" using search.
DSA C
Hint

Use printf to display the phone number found by search. Remember to check if the result is NULL.