Check if two strings are anagrams I'm doing some practice questions from the book Cracking the coding interview and wanted to get some people to review my code for bugs and optimizations.

Question:


  Write a method to decide if two strings are anagrams or not.


/*
Time complexity: O(n^2)
Space complexity: O(n)
*/
bool IsAnagram(std::string str1, std::string str2)
{
    if(str1.length() != str2.length())
        return false;
    for(int i = 0; i &lt; str1.length();i++)
    {
        bool found = false;
        int j = 0;
        while(!found &amp;&amp; j &lt; str2.length())
        {
            if(str1[i] == str2[j])
            {
                found = true;
                str2[j] = NULL;
            }
            j++;
        }
        if(!found)
            return false;
    }
    return true;
}
Since you only modify a copy of the second string, the first one should be a const reference:

bool IsAnagram(const std::string &amp;str1, std::string str2)


Also, i and j should be of type size_t to match what they're compared with.

However, I think I'd do it like this:

bool IsAnagram2(std::string str1, std::string str2)
{
    std::sort(str1.begin(), str1.end());
    std::sort(str2.begin(), str2.end());
    return str1==str2;
}


Test program:

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;algorithm&gt;

#define SHOW(x) std::cout &lt;&lt; # x " = " &lt;&lt; x &lt;&lt; '\n'

int main()
{
    std::cout &lt;&lt; std::boolalpha;
    SHOW(IsAnagram("\0\0\0\0\0", "\0lehl")); 
    SHOW(IsAnagram("hello", "")); 
    SHOW(IsAnagram("\0\0\0\0\0", "olehl")); 
    SHOW(IsAnagram("hello", "ole")); 
    SHOW(IsAnagram("hello", "plehl")); 
    SHOW(IsAnagram("hello", "hello")); 
    SHOW(IsAnagram("hello", "12345")); 
    SHOW(IsAnagram("hello", "Hello"));
    SHOW(IsAnagram("hello", "oellh"));
    SHOW(IsAnagram("hello", "olelh"));
    SHOW(IsAnagram("hello", "elelh"));
}


Program output

IsAnagram("\0\0\0\0\0", "\0lehl") = true
IsAnagram("hello", "") = false
IsAnagram("\0\0\0\0\0", "olehl") = false
IsAnagram("hello", "ole") = false
IsAnagram("hello", "plehl") = false
IsAnagram("hello", "hello") = true
IsAnagram("hello", "12345") = false
IsAnagram("hello", "Hello") = false
IsAnagram("hello", "oellh") = true
IsAnagram("hello", "olelh") = true
IsAnagram("hello", "elelh") = false