Checking if two strings are anagrams
Dos and donts

Don't use using namespace std. It's fine for very small programs, but std:: immediately tells someone that you're using a standard function and not some self-written sort.

Use all #include's necessary. std::sort is defined in &lt;algorithm&gt;. It seems like your C++ distribution includes &lt;algorithm&gt; or stl_algo in one of the other headers. That's not portable.

Use proper names. anagram doesn't tell anything about the function. Does it create an anagram? Does it check whether something is an anagram of something else? are_anagrams or something similar is less ambiguous.

The issue of \$\mathcal O(1) \$

You cannot get \$\mathcal O(1)\$ for this. You have to view each letter in each word at least once, therefore ending up with \$\mathcal O(n+m)\$ if one.size() \$\mathcal O(n)\$ and two.size() is \$\mathcal O(m)\$. However, since one.size() == two.size() \$n = m\$, otherwise we can find an answer in \$\mathcal O(1) \$.

Regardless, you can solve this in \$\mathcal O(1)\$ additional memory, if you use std::array&lt;int, 128&gt; or another fixed/variable size \$O(1)\$ indexable container:

typedef std::array&lt;int, 256&gt; character_count_type;

bool is_anagram(const std::string &amp; one, const std::string &amp; two)
{
    if(one.size() != two.size())
    {
        return false;
    }
    character_count_type character_count_one;
    character_count_type character_count_two;

    for(std::size_t i = 0; i &lt; one.size(); ++i){
        assert(0 &lt;= one[i] &amp;&amp; one[i] &lt; 256);
        assert(0 &lt;= two[i] &amp;&amp; two[i] &lt; 256);
        character_count_one[one[i]]++;
        character_count_two[two[i]]++;
    }
    return character_count_one == character_count_two;
}


This has \$\mathcal O(n)\$ worst time complexity, and due to the constant size of std::array&lt;...&gt; \$\mathcal O(1)\$ additional space.