Algorithm to check if one string is combination of other (Anagram)

Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation and capitalization. Each letter should have the same count in both strings. For example, ‘Eleven plus two’ and ‘Twelve plus one’ are meaningful anagrams of each other. Below is the code sample

        /// <summary>
        /// Determines whether first string is permutations of second one.
        /// We simply iterate through this code, counting how many times each character appears.
        /// Then, afterwards, we compare the two arrays.
        /// </summary>
        /// <param name="first">The first.</param>
        /// <param name="second">The second.</param>
        /// <returns></returns>
        public static bool IsStringPermutationOfOther(string first, string second)
            if (first.Length != second.Length)
                return false;

            //There are only 256 unique ASCII characters
            int[] characterCounts = new int[256];

            foreach (char c in first)

            foreach (char c in second)
                if (--characterCounts[(int)c] < 0)
                    return false;
            return true;

For following test strings

            Console.WriteLine(IsStringPermutationOfOther("Amol", "lomA"));
            Console.WriteLine(IsStringPermutationOfOther("Amol", "Amol"));
            Console.WriteLine(IsStringPermutationOfOther("Amol", "Amol   "));
            Console.WriteLine(IsStringPermutationOfOther("eleven plus two", "twelve plus one"));

It Returns

  • True
  • True
  • False
  • True

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s