Anagram Strings

An anagram[1] string is a string that can be formed by rearranging the letters of another string. In other words, if two strings are anagrams of each other, they contain exactly the same letters but in a different order.

Question: Check whether two strings are anagrams of each other

Method 1 Sorting

Sort the string and compare each characters.

bool areAnagram(string &str1, string &str2) {
	int M = str1.size();
	int N = str2.size();
	if (M != N) return false;
	sort(str1.start(), str1.end());
	sort(str2.start(), str2.end());
	return std::equal(str1.begin(), str1.end(), str2.begin());
}
Type Complexity
Time O(N×logN)
Space O(N)

Method 2 - HashMap

We can use hash map, like map or set, to check string is anagram or not. Store the count of each characters in string1 and string2. Compare the count is matched or not.

bool areAnagram(string &str1, string &str2) {
	unordered_map<char, int> count1, count2;
	for (char c : str1) {
		count1[c]++;
	}
	for (char c : str2) {
		count2[c]++;
	}
	return count1 == count2;
}
Type Complexity
Time O(N)
Space O(N)

  1. https://en.wikipedia.org/wiki/Anagram ↩︎