DEV Community

Stylus07
Stylus07

Posted on

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)

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const isAnagram = (s,t,f=i=>[...i].sort().join(''))=>f(s)==f(t)
const isAnagram = (s,t)=>''+[...s].sort()==[...t].sort()
Enter fullscreen mode Exit fullscreen mode

😝