242 Valid Anagram

Problem Statement

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.

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

Approach

Solution

const isAnagram = (s, t) => {
    if (s.length !== t.length) return false;

    let charCount = {};

    for (let i = 0; i < s.length; i++) {
        const charS = s[i];
        const charT = t[i];

        charCount[charS] = charCount[charS] ? charCount[charS] + 1 : 1;
        charCount[charT] = charCount[charT] ? charCount[charT] - 1 : -1;
    }

    for (let key in charCount) {
        if (charCount[key] !== 0) {
            return false;
        }
    }

    return true;
};

Questions

References

DSA MOC
for...in
Hashmap