Drill

ProblemsC++ › warmup

Are these two an anagram

mediumwarmupHash mapsStringsSortingC++

A word game checks whether one phrase uses exactly the same letters as another.

isAnagram(text: string, other: string) → bool

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

bool isAnagram(std::string text, std::string other) {
    
}

Worked examples

CallResult
isAnagram(std::string("Listen"), std::string("Silent"))true
isAnagram(std::string("a b"), std::string("ba"))true
isAnagram(std::string("hello"), std::string("world"))false
isAnagram(std::string("abc"), std::string("ab"))false

Hint

Strip and lowercase both, then compare the sorted characters, or count them.

Reference solution in C++
bool isAnagram(std::string text, std::string other) {
    auto clean = [](const string& s) {
        string r;
        for (char c : s) {
            if (isspace(static_cast<unsigned char>(c))) continue;
            r += static_cast<char>(tolower(static_cast<unsigned char>(c)));
        }
        std::sort(r.begin(), r.end());
        return r;
    };
    return clean(text) == clean(other);
}

The same problem in another language

More warmup problems in C++