Bird
Raised Fist0
DSA Cprogramming~10 mins

HashMap Implementation from Scratch in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - HashMap Implementation from Scratch
Initialize HashMap with buckets
↓
Compute hash(key) to find bucket index
↓
Check bucket for key existence
↓
Update value
↓
Done
Shows how a key-value pair is added or updated by hashing the key, locating the bucket, and inserting or updating the node.
Execution Sample
DSA C
hashMapPut(map, "apple", 10);
hashMapPut(map, "banana", 20);
hashMapPut(map, "apple", 30);
hashMapPrint(map);
Inserts 'apple' and 'banana' keys with values, then updates 'apple' value, finally prints the map.
Execution Table
StepOperationBucket IndexBucket Nodes BeforeActionBucket Nodes AfterVisual State
1Insert ('apple', 10)2[]Insert new node[('apple',10)][Bucket 2]: ('apple',10) -> null
2Insert ('banana', 20)0[]Insert new node[('banana',20)][Bucket 0]: ('banana',20) -> null
3Insert ('apple', 30)2[('apple',10)]Update value[('apple',30)][Bucket 2]: ('apple',30) -> null
4Print map----Bucket 0: ('banana',20) -> null Bucket 2: ('apple',30) -> null
5End----No more operations
💡 All insertions done and map printed
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
map.buckets[0][][][('banana',20)][('banana',20)][('banana',20)]
map.buckets[2][][('apple',10)][('apple',10)][('apple',30)][('apple',30)]
map.size01222
Key Moments - 3 Insights
Why do we update the value instead of adding a new node when the key exists?
Because the hash function points to the same bucket and the key is found in that bucket's linked list, we update the existing node's value to avoid duplicate keys, as shown in step 3 of the execution_table.
What happens if two different keys hash to the same bucket?
They are stored in the same bucket as a linked list of nodes. Each node holds a key-value pair. This chaining handles collisions, as seen in steps 1 and 2 where different keys go to different buckets, but if they collided, they would be linked.
Why do we need to compute the bucket index using a hash function?
The hash function converts the key into an index to quickly find the bucket where the key-value pair should be stored or searched, making operations efficient. This is shown in the 'Bucket Index' column in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the bucket index for key 'apple'?
A0
B1
C2
D3
💡 Hint
Check the 'Bucket Index' column for step 3 in the execution_table.
At which step does the map size increase?
AStep 3 only
BStep 1 and Step 2
CStep 4
DStep 3 and Step 4
💡 Hint
Look at the 'map.size' row in variable_tracker after each step.
If we insert a new key that hashes to bucket 2, what will happen to the bucket nodes?
AThe new node will be added to the linked list in bucket 2
BThe new node will replace the existing node
CThe bucket will be cleared before insertion
DInsertion will fail due to collision
💡 Hint
Recall how collisions are handled by chaining in the execution_table and concept_flow.
Concept Snapshot
HashMap stores key-value pairs using an array of buckets.
Keys are hashed to find bucket index.
If key exists in bucket, update value.
If not, insert new node in bucket's linked list.
Handles collisions by chaining nodes in buckets.
Operations: put, get, remove run in average O(1) time.
Full Transcript
This visual trace shows how a HashMap stores and updates key-value pairs. First, the map is initialized with empty buckets. When inserting a key, the hash function computes the bucket index. If the key is found in that bucket's linked list, its value is updated. Otherwise, a new node is inserted at the bucket. Collisions are handled by chaining nodes in the same bucket. The example inserts 'apple' and 'banana', then updates 'apple'. The final print shows the stored pairs. Variables track bucket contents and map size after each step.

Practice

(1/5)
1. What is the main purpose of a hash function in a HashMap implementation?
easy
A. To sort the keys in ascending order
B. To store values in a linked list
C. To convert a key into an index for storing the value
D. To delete keys from the HashMap

Solution

  1. Step 1: Understand the role of a hash function

    A hash function takes a key and converts it into a number (index) that tells where to store the value in the HashMap's internal array.
  2. Step 2: Compare other options

    Sorting keys or deleting keys are not the job of the hash function. Storing values in a linked list is a collision handling method, not hashing.
  3. Final Answer:

    To convert a key into an index for storing the value -> Option C
  4. Quick Check:

    Hash function = key to index [OK]
Hint: Hash function maps keys to array indexes fast [OK]
Common Mistakes:
  • Thinking hash function sorts keys
  • Confusing hash function with collision handling
  • Believing hash function deletes keys
2. Which of the following is the correct way to declare a simple HashMap structure in C that stores integer keys and values?
easy
A. typedef struct { int key; int value; } HashNode;
B. typedef struct { char* key; int value; } HashMap;
C. typedef struct { int key; int value; } HashMap;
D. typedef struct { int key; int value; HashNode* next; } HashMap;

Solution

  1. Step 1: Identify the basic node structure

    A HashMap stores key-value pairs. A node with int key and int value is a basic unit, so HashNode struct is correct.
  2. Step 2: Check other options

    typedef struct { char* key; int value; } HashMap; uses char* key which is not integer keys. typedef struct { int key; int value; } HashMap; names the struct HashMap but it's actually a node. typedef struct { int key; int value; HashNode* next; } HashMap; adds a pointer for chaining but names it HashMap, which is confusing.
  3. Final Answer:

    typedef struct { int key; int value; } HashNode; -> Option A
  4. Quick Check:

    Node struct with int key and value = typedef struct { int key; int value; } HashNode; [OK]
Hint: Node struct holds key and value pairs [OK]
Common Mistakes:
  • Confusing node and map struct names
  • Using wrong key types
  • Missing pointer for chaining in basic struct
3. Given the following code snippet for inserting keys into a HashMap with size 5, what will be the index for key 12?
int hash(int key) {
    return key % 5;
}

int index = hash(12);
printf("%d", index);
medium
A. 4
B. 2
C. 3
D. 1

Solution

  1. Step 1: Apply the hash function to key 12

    The hash function returns key % 5. For key 12, 12 % 5 = 2.
  2. Step 2: Confirm the printed index

    The code prints the index, which is 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    12 % 5 = 2 [OK]
Hint: Modulo operator gives index in hash function [OK]
Common Mistakes:
  • Calculating 12 % 5 incorrectly
  • Confusing modulo with division
  • Ignoring hash function logic
4. Consider this buggy code snippet for inserting a key-value pair into a HashMap with chaining:
void insert(HashNode** table, int size, int key, int value) {
    int index = key % size;
    HashNode* newNode = malloc(sizeof(HashNode));
    newNode->key = key;
    newNode->value = value;
    newNode->next = NULL;

    if (table[index] == NULL) {
        table[index] = newNode;
    } else {
        table[index]->next = newNode;
    }
}
What is the main problem in this code?
medium
A. It overwrites the existing chain instead of appending correctly
B. It does not handle memory allocation failure
C. It uses wrong hash function
D. It does not set the key and value fields

Solution

  1. Step 1: Analyze insertion logic for chaining

    If the bucket is empty, it sets the new node. Otherwise, it sets table[index]->next = newNode, which overwrites the existing next pointer, losing the chain.
  2. Step 2: Identify correct chaining method

    To append, it should traverse to the last node in the chain and then add the new node, not overwrite the first node's next pointer.
  3. Final Answer:

    It overwrites the existing chain instead of appending correctly -> Option A
  4. Quick Check:

    Chaining requires appending, not overwriting [OK]
Hint: Traverse chain to append new node, don't overwrite next [OK]
Common Mistakes:
  • Ignoring chain traversal
  • Assuming single node per bucket
  • Not checking for NULL before insertion
5. You want to implement a HashMap from scratch in C that supports integer keys and values, handles collisions using chaining, and dynamically resizes when load factor exceeds 0.7. Which of the following steps is NOT necessary for this implementation?
hard
A. Resize the internal array and rehash all keys when load factor is high
B. Create linked lists at each bucket to handle collisions
C. Implement a hash function to convert keys to indexes
D. Sort the keys in each bucket to speed up search

Solution

  1. Step 1: Understand necessary components of HashMap

    A hash function, chaining with linked lists, and resizing with rehashing are all essential for correct and efficient HashMap behavior.
  2. Step 2: Evaluate sorting keys in buckets

    Sorting keys in buckets is not required because chaining uses linked lists and search is done by traversing nodes. Sorting adds unnecessary overhead.
  3. Final Answer:

    Sort the keys in each bucket to speed up search -> Option D
  4. Quick Check:

    Sorting buckets is unnecessary in chaining [OK]
Hint: Chaining uses linked lists; sorting buckets is extra work [OK]
Common Mistakes:
  • Thinking sorting improves chaining search
  • Ignoring rehashing on resize
  • Skipping collision handling
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard