HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Checking if two strings are an anagram

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arecheckingtwoanagramstrings

Problem

This is my sample code to check if a given pair of strings are anagram or not.

static bool AreAnagram(string s1, string s2)
      {

        if (s1.Length != s2.Length)
            return false;

        foreach (char c in s1)
        {
            int ix = s2.IndexOf(c);

            if (ix == -1)
                return false;
        }

        return true;
    }


The complexity of this approach is \$O(n)\$.

What boundary conditions am I missing? Can it be made better?

Solution

You're missing the case where a word has more than one of the same characters.

For instance, the strings "aba" and "bab" would be seen as an anagram by your algorithm.

You can fix this by removing the found character from the string.

Additionally, if you wanted to make your algorithm faster, you could check if both strings are the same (and return true if they are) before checking the length. This is only a valid option if this is a likely scenario, because otherwise you'll be slowing down each anagram check.

Context

StackExchange Code Review Q#59370, answer score: 19

Revisions (0)

No revisions yet.