Valid Anagram

styluso7

Stylus07

Posted on April 11, 2022

Valid Anagram

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.


var isAnagram = function (s, t) {
    if (s.length !== t.length) {
        return false;
    }
    let countS = new Map();
    let countT = new Map();
    for (let start = 0; start < s.length; start++) {
        countS.set(s[start], 1 + (countS.get(s[start]) ? countS.get(s[start]) : 0));
        countT.set(t[start], 1 + (countT.get(t[start]) ? countT.get(t[start]) : 0));
    }

    for (const [key, value] of countS) {
        if (countS.get(key) !== countT.get(key)) {
            return false;
        }
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(n)
Space Complexity : O(s+t)

💖 💪 🙅 🚩
styluso7
Stylus07

Posted on April 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Valid Anagram
leetcode Valid Anagram

April 11, 2022