Group anagrams

We receive two strings, s1 and s2. We need to check if there are an anagram. An anagram of two words is something that has the exact same amount of characters in a string.

Example 1:

str1 = "aab"
str2 = "baa"

This would be an anagram.

Example 2:

str1 = "caab"
str2 = "baa"

This would be no anagram.


Solution

A solution to this problem is to check if both strings have the same length. If that is not the case they cannot be anagrams.

After that we can sort both string and then compare them. If they are the same, they are anagrams.

Complexity Value
TIME O(n log n + m log m)
SPACE O(1) or O(n+m) depending on the sorting algorithm
bool is_anagram(std::string s1, std::string s2) {
    if (s1.size() != s2.size()) return false;

    std::sort(s1.begin(), s1.end());
    std::sort(s2.begin(), s2.end());

    return s1 == s2;
}
def is_anagram(s1, s2):
    if len(s1) != len(s2):
        return False

    return sorted(s1) == sorted(s2)