How to group Anagrams from an array of strings in C++

1 Answer

0 votes
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <unordered_map>

std::vector<std::vector<std::string>> groupAnagrams(const std::vector<std::string>& strs) {
    std::unordered_map<std::string, std::vector<std::string>> anagramMap;

    for (const auto& str : strs) {
        std::string sortedStr = str;
        std::sort(sortedStr.begin(), sortedStr.end()); // Sort the string
        anagramMap[sortedStr].push_back(str); // Group by sorted string
    }

    std::vector<std::vector<std::string>> result;
    for (const auto& pair : anagramMap) {
        result.push_back(pair.second); // Collect grouped anagrams
    }

    return result;
}

int main() {
    std::vector<std::string> input = {"eat", "tea", "tan", "ate", "nat", "bat", "tae"};
    auto groupedAnagrams = groupAnagrams(input);

    for (const auto& group : groupedAnagrams) {
        for (const auto& word : group) {
            std::cout << word << " ";
        }
        std::cout << std::endl;
    }
}



/*
run:

bat 
tan nat 
eat tea ate tae 

*/

 



answered Jun 9, 2025 by avibootz
...