Bird
Raised Fist0
DSA Cprogramming

Why Hash Map Exists and What Problem It Solves in DSA C - Why This Pattern

Choose your learning style10 modes available
Mental Model
A hash map helps us find things quickly by using a special code to jump directly to where the item is stored.
Analogy: Imagine a huge library where books are scattered randomly. Without a system, you search shelf by shelf. A hash map is like having a special code on each book that tells you exactly which shelf and spot to look at instantly.
Keys: [apple, banana, grape]
Hash Map Buckets:
[0] -> null
[1] -> banana -> null
[2] -> apple -> null
[3] -> grape -> null
Dry Run Walkthrough
Input: Store keys: apple, banana, grape; then find 'banana'
Goal: Show how hash map stores keys and finds 'banana' quickly without checking all keys
Step 1: Calculate hash for 'apple' and store it in bucket 2
Buckets:
[0] -> null
[1] -> null
[2] -> apple -> null
[3] -> null
Why: We use the hash to decide where to put 'apple' so we can find it fast later
Step 2: Calculate hash for 'banana' and store it in bucket 1
Buckets:
[0] -> null
[1] -> banana -> null
[2] -> apple -> null
[3] -> null
Why: Each key gets its own bucket based on hash to avoid searching all keys
Step 3: Calculate hash for 'grape' and store it in bucket 3
Buckets:
[0] -> null
[1] -> banana -> null
[2] -> apple -> null
[3] -> grape -> null
Why: Storing keys in different buckets keeps lookups fast
Step 4: To find 'banana', calculate its hash to get bucket 1 and check keys there
Buckets:
[0] -> null
[1] -> [search banana] -> null
[2] -> apple -> null
[3] -> grape -> null
Why: We jump directly to bucket 1 instead of checking all buckets
Step 5: Find 'banana' in bucket 1 and return it
Buckets:
[0] -> null
[1] -> banana -> null
[2] -> apple -> null
[3] -> grape -> null
Why: Found the key quickly without searching other buckets
Result:
Buckets:
[0] -> null
[1] -> banana -> null
[2] -> apple -> null
[3] -> grape -> null
Found key: banana
Annotated Code
DSA C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 4

// Node for linked list in each bucket
typedef struct Node {
    char key[20];
    struct Node* next;
} Node;

// Hash Map with buckets
Node* hashMap[SIZE];

// Simple hash function: sum of chars mod SIZE
unsigned int hash(char* key) {
    unsigned int sum = 0;
    for (int i = 0; key[i] != '\0'; i++) {
        sum += key[i];
    }
    return sum % SIZE;
}

// Insert key into hash map
void insert(char* key) {
    unsigned int index = hash(key); // get bucket index
    Node* newNode = malloc(sizeof(Node));
    strcpy(newNode->key, key);
    newNode->next = hashMap[index]; // insert at head
    hashMap[index] = newNode;
}

// Search key in hash map
Node* search(char* key) {
    unsigned int index = hash(key); // get bucket index
    Node* curr = hashMap[index];
    while (curr != NULL) {
        if (strcmp(curr->key, key) == 0) {
            return curr; // found key
        }
        curr = curr->next; // check next node
    }
    return NULL; // not found
}

// Print hash map state
void printHashMap() {
    for (int i = 0; i < SIZE; i++) {
        printf("[%d] -> ", i);
        Node* curr = hashMap[i];
        while (curr != NULL) {
            printf("%s -> ", curr->key);
            curr = curr->next;
        }
        printf("null\n");
    }
}

int main() {
    // Initialize buckets
    for (int i = 0; i < SIZE; i++) {
        hashMap[i] = NULL;
    }

    // Insert keys
    insert("apple");
    insert("banana");
    insert("grape");

    // Print state after inserts
    printHashMap();

    // Search for 'banana'
    Node* found = search("banana");
    if (found != NULL) {
        printf("Found key: %s\n", found->key);
    } else {
        printf("Key not found\n");
    }

    return 0;
}
unsigned int index = hash(key); // get bucket index
calculate bucket index using hash function
newNode->next = hashMap[index]; // insert at head
insert new key at the start of the bucket list
Node* curr = hashMap[index];
start searching from the bucket's head
if (strcmp(curr->key, key) == 0) { return curr; }
check if current node key matches search key
curr = curr->next; // check next node
move to next node if not found
OutputSuccess
[0] -> null [1] -> banana -> null [2] -> apple -> null [3] -> grape -> null Found key: banana
Complexity Analysis
Time: O(1) average because hash function jumps directly to bucket; worst O(n) if many keys collide in one bucket
Space: O(n) because we store all keys in buckets
vs Alternative: Compared to searching all keys one by one (O(n)), hash map reduces average search time to O(1) by using hashing
Edge Cases
Empty hash map
Search returns not found immediately because buckets are empty
DSA C
while (curr != NULL) { ... }
Multiple keys hashing to same bucket (collision)
Keys are stored in linked list in that bucket; search checks each node
DSA C
curr = curr->next; // check next node
Searching for a key not present
Search traverses bucket list and returns NULL
DSA C
return NULL; // not found
When to Use This Pattern
When you need to store and find items quickly by key without scanning all items, reach for the hash map pattern because it uses hashing to jump directly to the data location.
Common Mistakes
Mistake: Not handling collisions, assuming each bucket holds only one key
Fix: Use a linked list or another structure in each bucket to store multiple keys
Mistake: Using a poor hash function causing many collisions
Fix: Use a hash function that distributes keys evenly across buckets
Summary
Hash map stores keys using a hash function to find them quickly.
Use hash maps when you want fast lookup, insert, and delete by key.
The key insight is hashing lets you jump directly to where the data is stored, avoiding slow searches.

Practice

(1/5)
1. Why do we use a hash map instead of a simple list to store key-value pairs?
easy
A. To quickly find values using keys without searching the entire list
B. To store values in sorted order automatically
C. To save memory by compressing data
D. To allow duplicate keys with different values

Solution

  1. Step 1: Understand list search time

    In a simple list, finding a value by key requires checking each item one by one, which takes longer as the list grows.
  2. Step 2: Understand hash map lookup

    A hash map uses a special function to jump directly to the value's location, making search very fast regardless of size.
  3. Final Answer:

    To quickly find values using keys without searching the entire list -> Option A
  4. Quick Check:

    Hash map = fast key lookup [OK]
Hint: Hash maps speed up key-based searches [OK]
Common Mistakes:
  • Thinking hash maps store data sorted automatically
  • Believing hash maps compress data to save memory
  • Assuming hash maps allow duplicate keys
2. Which of the following is the correct syntax to declare a hash map in C using a struct and array?
easy
A. struct HashMap { int key; int value; } map[100];
B. HashMap map = new HashMap();
C. hash_map map;
D. map = {};

Solution

  1. Step 1: Recognize C syntax for struct arrays

    In C, a hash map can be represented as an array of structs with key and value fields.
  2. Step 2: Check options for valid C declaration

    struct HashMap { int key; int value; } map[100]; correctly declares a struct and an array of 100 elements. Other options use syntax from other languages or invalid C syntax.
  3. Final Answer:

    struct HashMap { int key; int value; } map[100]; -> Option A
  4. Quick Check:

    C struct array = struct HashMap { int key; int value; } map[100]; [OK]
Hint: C uses structs and arrays for hash maps [OK]
Common Mistakes:
  • Using C++ or Java syntax in C code
  • Trying to declare hash maps without structs
  • Using empty braces {} for initialization
3. Consider this simplified hash map code in C that stores keys and values:
struct Entry { int key; int value; };
struct Entry map[5] = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}};

int findValue(int key) {
  for (int i = 0; i < 5; i++) {
    if (map[i].key == key) return map[i].value;
  }
  return -1;
}

int main() {
  printf("%d", findValue(3));
  return 0;
}
What is the output when this program runs?
medium
A. 3
B. -1
C. 30
D. Compilation error

Solution

  1. Step 1: Understand the findValue function

    The function loops through the map array and returns the value where the key matches the input.
  2. Step 2: Trace the call findValue(3)

    It finds key 3 at index 2 with value 30 and returns it. So printf prints 30.
  3. Final Answer:

    30 -> Option C
  4. Quick Check:

    Key 3 value = 30 [OK]
Hint: Loop finds key, returns matching value [OK]
Common Mistakes:
  • Confusing key with value in output
  • Assuming function returns key instead of value
  • Expecting compilation error due to struct
4. This code tries to find a value by key in a hash map but has a bug:
struct Entry { int key; int value; };
struct Entry map[3] = {{1, 100}, {2, 200}, {3, 300}};

int findValue(int key) {
  for (int i = 0; i <= 3; i++) {
    if (map[i].key == key) return map[i].value;
  }
  return -1;
}
What is the bug and how to fix it?
medium
A. The key comparison uses '==' instead of '='; replace '==' with '='
B. The struct is missing a constructor; add one to fix it
C. The return type should be void; change int to void
D. The loop goes out of bounds; change 'i <= 3' to 'i < 3' to fix it

Solution

  1. Step 1: Check loop bounds

    The array has 3 elements indexed 0,1,2. Loop with 'i <= 3' accesses map[3], which is out of bounds.
  2. Step 2: Fix loop condition

    Change loop to 'i < 3' to stay within valid indices and avoid runtime errors.
  3. Final Answer:

    The loop goes out of bounds; change 'i <= 3' to 'i < 3' to fix it -> Option D
  4. Quick Check:

    Loop bounds must match array size [OK]
Hint: Array index must be less than size, not less or equal [OK]
Common Mistakes:
  • Ignoring array bounds causing crashes
  • Confusing assignment '=' with comparison '=='
  • Changing return type unnecessarily
5. You want to store student IDs and their grades using a hash map in C. Which problem does using a hash map solve best compared to an array or list? A student ID is a large number and not continuous. Options: A) Allow multiple students to share the same ID B) Automatically sort students by their grades C) Save memory by storing only unique grades D) Quickly find a student's grade by their ID without searching all entries
hard
A. Allow multiple students to share the same ID
B. Quickly find a student's grade by their ID without searching all entries
C. Save memory by storing only unique grades
D. Automatically sort students by their grades

Solution

  1. Step 1: Understand the problem with large, non-continuous keys

    Arrays or lists require searching or large memory if keys are large and sparse.
  2. Step 2: How hash maps help

    Hash maps use a function to map large keys to storage locations, enabling fast lookup without scanning all data.
  3. Final Answer:

    Quickly find a student's grade by their ID without searching all entries -> Option B
  4. Quick Check:

    Hash map = fast lookup for large keys [OK]
Hint: Hash maps handle large keys efficiently [OK]
Common Mistakes:
  • Thinking hash maps sort data automatically
  • Believing hash maps compress data to save memory
  • Assuming duplicate keys are allowed
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