AlgoDaily 04: Is An Anagram

https://algodaily.com/challenges/is-an-anagram

“Here’s the definition of an anagram: a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

We are given two strings like “cinema” and “iceman” as inputs. Can you write a method isAnagram(str1, str2) that will return true or false depending on whether the strings are anagrams of each other?”

The gotcha with this is being careful with multiple instances of the same letter, i.e. you can’t just check that each character is also found in the other string.

Duplicate detection or needing to handle duplicates often suggests sorting (e.g. Unix’s sort -u) as a solution.

function isAnagram(str1, str2) {
	if (str1.length !== str2.length) {
		return false;
	}

	if (str1 === str2) {
		return true;
	}

	return [...str1.toLowerCase()].sort().join('') === [...str2.toLowerCase()].sort().join('');
}

The extra checks at the beginning aren’t necessary but might be faster with large strings.

This is the same solution suggested by Algo Daily.


View post: AlgoDaily 04: Is An Anagram