Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Home » C++ » Solved Programs on C++ » Removing Anagrams from String

C++ program to remove anagrams from a vector of strings

Anagram example: [Earth, Heart], [Top, pot, Opt]
// Tips: 1. Ask clarifying questions.
// 2. Think out loud.
// 3. Pay close attention to the performance of your final solution


/**
* Removes anagrams from a vector of strings
* @var words The input vector of strings
*/
void removeAnagrams(std::vector& words) {

    std::map sortedMap;
    std::map counter;

    const auto sortWord = [](const std::string& word) {
        std::string sorted = word;
        std::sort(sorted.begin(), sorted.end());
        return sorted;
    };

    for (const auto& word : words) {
        const auto& sortedWord = sortWord(word);
        sortedMap[word] = sortedWord;
        counter[sortedWord]++;
    }

    words.erase(remove_if(words.begin(), words.end(),
                          [&](const std::string& s){
                                return counter[sortedMap[s]] > 1;
                          }),
                          words.end());
}

int main()
{
    std::vector input{"abc", "cba", "bca", "abcd", "cdb", "abcc", "acc", "", "aab", "bca", "bcd"};
    removeAnagrams(input);
    for (auto s : input) {
        std::cout << s << std::endl;
    }

    return 0;
}

Execution of the program

C++ program to remove anagrams from a vector of strings