Bird
Raised Fist0
DSA C++programming

Group Anagrams Using Hash Map in DSA C++

Choose your learning style10 modes available
Mental Model
Group words that have the same letters by sorting them and using the sorted word as a key.
Analogy: Imagine sorting letters of each word like arranging colored beads in order. Words with the same beads in the same order belong to the same group.
words: ["eat", "tea", "tan", "ate", "nat", "bat"]

hash map:
{
  "aet" -> ["eat", "tea", "ate"],
  "ant" -> ["tan", "nat"],
  "abt" -> ["bat"]
}
Dry Run Walkthrough
Input: list: ["eat", "tea", "tan", "ate", "nat", "bat"]
Goal: Group words that are anagrams together using a hash map
Step 1: Take first word "eat", sort letters to get "aet", add "eat" to hash map under key "aet"
{"aet": ["eat"]}
Why: Sorting letters creates a unique key for all anagrams
Step 2: Take second word "tea", sort letters to get "aet", add "tea" to existing list under key "aet"
{"aet": ["eat", "tea"]}
Why: Words with same sorted letters belong to same group
Step 3: Take third word "tan", sort letters to get "ant", add "tan" to hash map under key "ant"
{"aet": ["eat", "tea"], "ant": ["tan"]}
Why: New sorted key means new group
Step 4: Take fourth word "ate", sort letters to get "aet", add "ate" to list under key "aet"
{"aet": ["eat", "tea", "ate"], "ant": ["tan"]}
Why: Add to existing anagram group
Step 5: Take fifth word "nat", sort letters to get "ant", add "nat" to list under key "ant"
{"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"]}
Why: Add to existing anagram group
Step 6: Take sixth word "bat", sort letters to get "abt", add "bat" to hash map under key "abt"
{"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"], "abt": ["bat"]}
Why: New group for different letters
Result:
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Annotated Code
DSA C++
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<vector<string>> groupAnagrams(vector<string>& strs) {
    unordered_map<string, vector<string>> hashMap;
    for (string& word : strs) {
        string sortedWord = word;
        sort(sortedWord.begin(), sortedWord.end()); // sort letters to get key
        hashMap[sortedWord].push_back(word); // group anagrams under sorted key
    }
    vector<vector<string>> result;
    for (auto& pair : hashMap) {
        result.push_back(pair.second); // collect grouped anagrams
    }
    return result;
}

int main() {
    vector<string> input = {"eat", "tea", "tan", "ate", "nat", "bat"};
    vector<vector<string>> groups = groupAnagrams(input);
    for (const auto& group : groups) {
        cout << "[";
        for (size_t i = 0; i < group.size(); ++i) {
            cout << group[i];
            if (i != group.size() - 1) cout << ", ";
        }
        cout << "]\n";
    }
    return 0;
}
sort(sortedWord.begin(), sortedWord.end()); // sort letters to get key
sort letters of current word to create unique key for anagram group
hashMap[sortedWord].push_back(word); // group anagrams under sorted key
add original word to list under sorted key in hash map
for (auto& pair : hashMap) { result.push_back(pair.second); }
collect all grouped anagrams from hash map into result vector
OutputSuccess
[eat, tea, ate] [tan, nat] [bat]
Complexity Analysis
Time: O(n * k log k) because we sort each of the n words of length k
Space: O(n * k) because we store all words grouped in hash map
vs Alternative: Naive approach compares each word with others, O(n^2 * k), much slower than hashing with sorting
Edge Cases
empty input list
returns empty list with no groups
DSA C++
for (string& word : strs) { ... } handles empty by skipping loop
list with one word
returns list with one group containing that word
DSA C++
hashMap[sortedWord].push_back(word); adds single word group
words with same letters but different cases
treated as different groups because sorting is case sensitive
DSA C++
sort(sortedWord.begin(), sortedWord.end()); does not normalize case
When to Use This Pattern
When you need to group words that are rearrangements of each other, use a hash map with sorted word keys to quickly group anagrams.
Common Mistakes
Mistake: Using the original word as key instead of the sorted word
Fix: Sort the word first to create the key before inserting into the hash map
Mistake: Not sorting the word before using as key
Fix: Always sort letters of the word to get the correct key for grouping
Summary
Groups words that have the same letters by sorting and hashing.
Use when you want to find all anagram groups in a list of words.
Sorting each word creates a unique key that identifies its anagram group.

Practice

(1/5)
1. What is the main idea behind grouping anagrams using a hash map?
easy
A. Use sorted strings as keys to group words with the same characters
B. Use the length of the string as the key to group words
C. Use the first character of the string as the key
D. Use the last character of the string as the key

Solution

  1. Step 1: Understand anagram grouping

    Anagrams have the same characters in different orders, so sorting the string gives a unique key for all anagrams.
  2. Step 2: Use sorted string as hash map key

    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 characters -> Option A
  4. Quick Check:

    Sorted string key = group anagrams [OK]
Hint: Sort each word to find its anagram group key [OK]
Common Mistakes:
  • Using string length as key misses different anagrams
  • Using first or last character groups unrelated words
  • Not sorting strings before using as keys
2. Which of the following C++ code snippets correctly declares a hash map to group anagrams where the key is a string and the value is a vector of strings?
easy
A. std::unordered_map anagramGroups;
B. std::map> anagramGroups;
C. std::unordered_map> anagramGroups;
D. std::unordered_map anagramGroups;

Solution

  1. Step 1: Identify key and value types

    The key should be a string (sorted word), and the value should be a vector of strings (group of anagrams).
  2. Step 2: Match correct declaration

    std::unordered_map> anagramGroups; uses unordered_map with key as string and value as vector<string>, which is correct for grouping anagrams.
  3. Final Answer:

    std::unordered_map> anagramGroups; -> Option C
  4. Quick Check:

    Key=string, Value=vector<string> [OK]
Hint: Use unordered_map for grouping [OK]
Common Mistakes:
  • Using int as key instead of string
  • Using vector<char> as key (not hashable)
  • Using string as value instead of vector<string>
3. What is the output of the following C++ code snippet?
std::vector words = {"eat", "tea", "tan", "ate", "nat", "bat"};
std::unordered_map> groups;
for (auto &word : words) {
    std::string sortedWord = word;
    std::sort(sortedWord.begin(), sortedWord.end());
    groups[sortedWord].push_back(word);
}
for (auto &pair : groups) {
    std::cout << "Group: ";
    for (auto &w : pair.second) std::cout << w << " ";
    std::cout << std::endl;
}
medium
A. Group: eat tea Group: tan bat Group: ate nat
B. Group: eat tea ate Group: tan nat Group: bat
C. Group: ate tea Group: bat tan Group: eat nat
D. Group: eat tan bat Group: tea nat ate

Solution

  1. Step 1: Sort each word and group by sorted key

    "eat", "tea", "ate" all sort to "aet" so grouped together; "tan", "nat" sort to "ant"; "bat" sorts to "abt".
  2. Step 2: Print groups

    Groups printed are: "eat tea ate", "tan nat", and "bat".
  3. Final Answer:

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

    Sorted keys group anagrams correctly [OK]
Hint: Sort words, group by sorted key, print groups [OK]
Common Mistakes:
  • Not sorting words before grouping
  • Mixing groups by original word order
  • Printing keys instead of grouped words
4. Identify the error in the following code snippet that tries to group anagrams:
std::vector words = {"abc", "bca", "cab"};
std::unordered_map> groups;
for (auto word : words) {
    std::string key = word;
    std::sort(word.begin(), word.end());
    groups[key].push_back(word);
}
medium
A. Sorting is done on 'word' but 'key' is used as map key, causing wrong grouping
B. The vector 'words' is not initialized correctly
C. The map should use vector<char> as key instead of string
D. The loop variable should be a reference to avoid copying

Solution

  1. Step 1: Analyze sorting and key usage

    The code sorts 'word' but uses 'key' (unsorted) as the map key, so grouping is incorrect.
  2. Step 2: Correct usage

    Sort 'key' and use it as the map key to group anagrams properly.
  3. Final Answer:

    Sorting is done on 'word' but 'key' is used as map key, causing wrong grouping -> Option A
  4. Quick Check:

    Sort key before using in map [OK]
Hint: Sort the key string, not the original word [OK]
Common Mistakes:
  • Sorting wrong variable before using as key
  • Using unsorted string as map key
  • Ignoring reference vs copy in loop
5. Given a list of strings, how would you modify the grouping anagrams approach to handle case-insensitive grouping (e.g., "Eat" and "tea" should be grouped together)?
hard
A. Sort strings without changing case
B. Use the original string as key without any changes
C. Group by string length only
D. Convert each string to lowercase before sorting and using as key

Solution

  1. Step 1: Normalize case for consistent keys

    Convert each string to lowercase so that case differences do not affect grouping.
  2. Step 2: Sort the lowercase string and use as key

    Sorting the lowercase string ensures all case variants of anagrams map to the same key.
  3. Step 3: Group anagrams using normalized keys

    Use the lowercase sorted string as the hash map key to group anagrams case-insensitively.
  4. Final Answer:

    Convert each string to lowercase before sorting and using as key -> Option D
  5. Quick Check:

    Lowercase + sort = case-insensitive grouping [OK]
Hint: Lowercase strings before sorting to ignore case [OK]
Common Mistakes:
  • Not normalizing case before grouping
  • Using original case strings as keys
  • Grouping by length or unsorted strings
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