Skip to main content

Valid Anagram

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

Solution

/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if (s.length !== t.length) {
return false;
}

const map = {};
for (let i = 0; i < s.length; i++) {
const c1 = s[i];
const c2 = t[i];
if (!(c1 in map)) {
map[c1] = 0;
}
if (!(c2 in map)) {
map[c2] = 0;
}
map[c1]++;
map[c2]--;
}
return Object.values(map).every(n => !n);
};

Use a hashmap map to keep track the number of times a character appears in s and t. More specifically, we add 1 if it appears in s, and subtract 1 if it appears in t. Thus, if every value in map is 0, s must be an anagram of t.