Algorithms

How to find if Two Strings are Anagrams of each other in C#?

In case you are not aware, Anagrams are strings whose characters are some permutation of each other.

For ex: cat, act, tac are anagrams as they are all permutations of ‘a’, ‘c’ and ‘t’.

Here’s the code which checks for the same:

public static bool AreTwoStringsAnagrams(string s1, string s2)
        {
            // Short circuit if any of the strings are null or whitespace 
            if (string.IsNullOrWhiteSpace(s1) || string.IsNullOrWhiteSpace(s2))
            {
                return false;
            }
 
            // Short circuit if the strings are not of equal length
            if (s1.Length != s2.Length)
            {
                return false;
            }
 
            // O(L) space complexity, where L is the Lenght of the largest string
            char[] c1 = s1.ToLower().ToCharArray();
            char[] c2 = s2.ToLower().ToCharArray();
 
            Array.Sort(c1);
            Array.Sort(c2);
 
            for(int i = 0; i < c1.Length; i++)
            {
                if (c1[i] != c2[i])
                {
                    return false;
                }
            }
 
            return true;
        }
Advertisements
Standard