Anagram (Hash)

Problem

Anagrams Two words are said to be anagrams when two strings differ in alphabetical order, but their composition matches.
For example, AbaAeCe and baeeACA have different alphabets, but if you look at their composition, they are A(2), a(1), b(1), C(1), e(2), the alphabets and their numbers all match. . In other words, if one word is rearranged, it becomes the other word, it is called an anagram.
Given two words of equal length, write a program to determine if they are anagrams. When identifying anagrams, case is sensitive.

input

  • The first word is entered on the first line, and the second word is entered on the second line
  • No more than 100 words in length
AbaAeCe
baeeACA

abaCC
Caaab

output

If the two words are anagrams, “YES” is output, otherwise “NO” is output.

YES

NO

Solution

Using Sort()

function solution(str1, str2) {
	let answer = 'YES';

	if (str1.length !== str2.length) answer = 'NO';

	const arr1 = str1.split('').sort();
	const arr2 = str2.split('').sort();

	for (let i in arr1) {
		if (arr1[i] !== arr2[i]) answer = 'NO';
	}

	return answer;
}

Use Map().set() & Map().get()

function solution(str1, str2) {
	let answer = 'YES';

	let sH = new Map();
	for (let x of str1) {
		if (sH.has(x)) sH.set(x, sH.get(x) + 1);
		else sH.set(x, 1);
	}

	for (let x of str2) {
		if (!sH.has(x) || sH.get(x) === 0) return 'No';
		sH.set(x, sH.get(x) - 1);
	}

	return answer;
}