Bird
Raised Fist0
DSA Cprogramming~20 mins

Group Anagrams Using Hash Map in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Anagram Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Grouping Anagrams by Sorted Key
What is the output of the following C code that groups anagrams using a hash map keyed by sorted strings?
DSA C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Simple hash map node for demonstration
typedef struct Node {
    char *key;
    char **words;
    int count;
    int capacity;
    struct Node *next;
} Node;

// Function to sort characters in a string
void sortString(char *str) {
    int len = strlen(str);
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (str[i] > str[j]) {
                char temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
}

// Insert word into hash map node
void insertWord(Node *node, char *word) {
    if (node->count == node->capacity) {
        node->capacity *= 2;
        node->words = realloc(node->words, node->capacity * sizeof(char*));
    }
    node->words[node->count++] = word;
}

// Simple hash function
unsigned int hash(char *str) {
    unsigned int h = 0;
    while (*str) {
        h = h * 31 + *str++;
    }
    return h % 10;
}

// Find or create node in hash map
Node* findOrCreate(Node **map, char *key) {
    unsigned int h = hash(key);
    Node *curr = map[h];
    while (curr) {
        if (strcmp(curr->key, key) == 0) return curr;
        curr = curr->next;
    }
    Node *newNode = malloc(sizeof(Node));
    newNode->key = strdup(key);
    newNode->capacity = 2;
    newNode->count = 0;
    newNode->words = malloc(newNode->capacity * sizeof(char*));
    newNode->next = map[h];
    map[h] = newNode;
    return newNode;
}

int main() {
    char *words[] = {"eat", "tea", "tan", "ate", "nat", "bat"};
    int n = 6;
    Node *map[10] = {0};

    for (int i = 0; i < n; i++) {
        char *copy = strdup(words[i]);
        sortString(copy);
        Node *node = findOrCreate(map, copy);
        insertWord(node, words[i]);
        free(copy);
    }

    // Print groups
    for (int i = 0; i < 10; i++) {
        Node *curr = map[i];
        while (curr) {
            printf("Group: ");
            for (int j = 0; j < curr->count; j++) {
                printf("%s ", curr->words[j]);
            }
            printf("\n");
            curr = curr->next;
        }
    }
    return 0;
}
A
Group: bat 
Group: tan 
Group: nat 
Group: eat 
Group: tea 
Group: ate 
B
Group: eat tea ate 
Group: bat 
Group: tan nat 
C
Group: bat 
Group: tan nat 
Group: eat tea ate 
D
Group: bat tan nat eat tea ate 
Attempts:
2 left
💡 Hint
Think about how sorting the characters in each word groups anagrams together.
🧠 Conceptual
intermediate
1:30remaining
Why Use Sorted Strings as Keys in Grouping Anagrams?
Why do we use the sorted version of a word as the key in a hash map when grouping anagrams?
ABecause sorting words makes them shorter and easier to store.
BBecause sorted strings are unique identifiers for anagram groups.
CBecause sorted strings are always the same length as original words.
DBecause sorting words removes duplicate letters.
Attempts:
2 left
💡 Hint
Think about what makes anagrams similar.
🔧 Debug
advanced
2:00remaining
Identify the Error in Hash Map Grouping Code
What error will this code produce when grouping anagrams using a hash map keyed by sorted strings?
DSA C
char *words[] = {"abc", "bca", "cab"};
Node *map[5] = {0};

for (int i = 0; i < 3; i++) {
    char *copy = strdup(words[i]);
    sortString(copy);
    Node *node = findOrCreate(map, copy);
    insertWord(node, copy);
    free(copy);
}
ANo error; code runs correctly.
BSegmentation fault because map size is too small.
CMemory leak because 'copy' is never freed.
DUse after free error due to freeing 'copy' after inserting it.
Attempts:
2 left
💡 Hint
Check what happens to 'copy' after inserting it into the node.
❓ Predict Output
advanced
2:00remaining
Output of Group Anagrams with Different Hash Function
What is the output of this code that groups anagrams using a hash map with a hash function returning constant 0?
DSA C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
    char *key;
    char **words;
    int count;
    int capacity;
    struct Node *next;
} Node;

void sortString(char *str) {
    int len = strlen(str);
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (str[i] > str[j]) {
                char temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
}

void insertWord(Node *node, char *word) {
    if (node->count == node->capacity) {
        node->capacity *= 2;
        node->words = realloc(node->words, node->capacity * sizeof(char*));
    }
    node->words[node->count++] = word;
}

unsigned int hash(char *str) {
    return 0; // constant hash to force collisions
}

Node* findOrCreate(Node **map, char *key) {
    unsigned int h = hash(key);
    Node *curr = map[h];
    while (curr) {
        if (strcmp(curr->key, key) == 0) return curr;
        curr = curr->next;
    }
    Node *newNode = malloc(sizeof(Node));
    newNode->key = strdup(key);
    newNode->capacity = 2;
    newNode->count = 0;
    newNode->words = malloc(newNode->capacity * sizeof(char*));
    newNode->next = map[h];
    map[h] = newNode;
    return newNode;
}

int main() {
    char *words[] = {"eat", "tea", "tan", "ate", "nat", "bat"};
    int n = 6;
    Node *map[1] = {0};

    for (int i = 0; i < n; i++) {
        char *copy = strdup(words[i]);
        sortString(copy);
        Node *node = findOrCreate(map, copy);
        insertWord(node, words[i]);
        free(copy);
    }

    Node *curr = map[0];
    while (curr) {
        printf("Group: ");
        for (int j = 0; j < curr->count; j++) {
            printf("%s ", curr->words[j]);
        }
        printf("\n");
        curr = curr->next;
    }
    return 0;
}
A
Group: bat 
Group: tan nat 
Group: eat tea ate 
B
Group: eat tea ate 
Group: bat 
Group: tan nat 
C
Group: bat tan nat eat tea ate 
D
Group: eat tea ate bat tan nat 
Attempts:
2 left
💡 Hint
All keys hash to the same bucket, so groups are stored in a linked list.
🚀 Application
expert
1:30remaining
Number of Unique Anagram Groups
Given the list of words {"listen", "silent", "enlist", "google", "gogole", "abc", "cab"}, how many unique anagram groups will be formed using a hash map keyed by sorted strings?
A3
B6
C5
D4
Attempts:
2 left
💡 Hint
Group words by their sorted letters and count distinct groups.

Practice

(1/5)
1. What is the main idea behind grouping anagrams using a hash map?
easy
A. Use the length of words as keys to group anagrams
B. Store words in a list without any sorting or grouping
C. Group words by their first character only
D. Use sorted strings as keys to group words with the same letters

Solution

  1. Step 1: Understand anagrams and their properties

    Anagrams are words made of the same letters in any order, so sorting letters gives a unique key for each group.
  2. Step 2: Use sorted strings as hash map keys

    By sorting each word and using it as a key, all anagrams map to the same key and can be grouped together.
  3. Final Answer:

    Use sorted strings as keys to group words with the same letters -> Option D
  4. Quick Check:

    Sorted word keys group anagrams [OK]
Hint: Sort each word and use as key to group anagrams [OK]
Common Mistakes:
  • Grouping by word length only
  • Using first character as key
  • Not sorting words before grouping
2. Which of the following is the correct way to declare a hash map (dictionary) in C for grouping anagrams?
easy
A. map anagramGroups;
B. unordered_map anagramGroups;
C. unordered_map anagramGroups;
D. vector<string> anagramGroups;

Solution

  1. Step 1: Identify the data types needed for grouping anagrams

    We need a map from a string key (sorted word) to a list of strings (anagrams).
  2. Step 2: Choose the correct C++ STL container

    unordered_map fits this need perfectly.
  3. Final Answer:

    unordered_map anagramGroups; -> Option B
  4. Quick Check:

    Map from string to vector<string> groups anagrams [OK]
Hint: Use unordered_map for grouping anagrams [OK]
Common Mistakes:
  • Using map which mismatches key and value types
  • Using vector<string> alone without mapping keys
  • Using unordered_map which is unrelated
3. What is the output of the following C++ code snippet? vector<string> words = {"eat", "tea", "tan", "ate", "nat", "bat"}; unordered_map groups; for (auto &word : words) { string sortedWord = word; sort(sortedWord.begin(), sortedWord.end()); groups[sortedWord].push_back(word); } for (auto &pair : groups) { sort(pair.second.begin(), pair.second.end()); for (auto &w : pair.second) cout << w << " "; cout << endl; }
medium
A. bat nat tan eat tea ate
B. eat tea ate bat tan nat
C. tea ate eat bat tan nat
D. ate eat tea bat nat tan

Solution

  1. Step 1: Group words by sorted keys

    Words "eat", "tea", "ate" all sort to "aet" and group together; "tan", "nat" to "ant"; "bat" to "abt".
  2. Step 2: Sort each group and print

    Each group is sorted alphabetically before printing: "ate eat tea", "bat", "nat tan".
  3. Final Answer:

    bat nat tan eat tea ate -> Option A
  4. Quick Check:

    Sorted keys group anagrams; groups sorted before print [OK]
Hint: Sort words and groups before printing for consistent output [OK]
Common Mistakes:
  • Not sorting groups before printing
  • Printing groups in wrong order
  • Confusing sorted keys with original words
4. Identify the bug in this C++ code for grouping anagrams: vector<string> words = {"abc", "bca", "cab"}; unordered_map groups; for (auto word : words) { string key = word; sort(word.begin(), word.end()); groups[key].push_back(word); }
medium
A. Sorting is done on 'word' but key uses unsorted string
B. Using unordered_map instead of map causes error
C. Loop variable should be reference to avoid copies
D. Missing initialization of groups map

Solution

  1. Step 1: Check how key and sorted string are assigned

    Key is assigned before sorting, so key is unsorted original word.
  2. Step 2: Sorting is done on 'word' but key remains unsorted

    Groups use unsorted key, so anagrams won't group correctly.
  3. Final Answer:

    Sorting is done on 'word' but key uses unsorted string -> Option A
  4. Quick Check:

    Key must be sorted string for correct grouping [OK]
Hint: Sort string before assigning key for hash map [OK]
Common Mistakes:
  • Assigning key before sorting
  • Sorting wrong variable
  • Not using reference in loop (less critical here)
5. Given a list of words, how can you modify the hash map grouping approach to handle case-insensitive anagrams (e.g., "Eat" and "tea" grouped together)?
hard
A. Group words by their first letter ignoring case
B. Use word length as key instead of sorted string
C. Convert all words to lowercase before sorting and grouping
D. Sort words without changing case and group normally

Solution

  1. Step 1: Understand case-insensitive grouping

    "Eat" and "tea" differ in case but are anagrams ignoring case.
  2. Step 2: Normalize words by converting to lowercase before sorting

    This ensures keys match regardless of original case.
  3. Final Answer:

    Convert all words to lowercase before sorting and grouping -> Option C
  4. Quick Check:

    Lowercase normalization groups case-insensitive anagrams [OK]
Hint: Lowercase words before sorting to group case-insensitive anagrams [OK]
Common Mistakes:
  • Grouping by length only
  • Ignoring case normalization
  • Sorting without case conversion
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