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.


This content originally appeared on DEV Community and was authored by Stylus07

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;
}

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


This content originally appeared on DEV Community and was authored by Stylus07


Print Share Comment Cite Upload Translate Updates
APA

Stylus07 | Sciencx (2022-04-11T03:10:33+00:00) Valid Anagram. Retrieved from https://www.scien.cx/2022/04/11/valid-anagram/

MLA
" » Valid Anagram." Stylus07 | Sciencx - Monday April 11, 2022, https://www.scien.cx/2022/04/11/valid-anagram/
HARVARD
Stylus07 | Sciencx Monday April 11, 2022 » Valid Anagram., viewed ,<https://www.scien.cx/2022/04/11/valid-anagram/>
VANCOUVER
Stylus07 | Sciencx - » Valid Anagram. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/11/valid-anagram/
CHICAGO
" » Valid Anagram." Stylus07 | Sciencx - Accessed . https://www.scien.cx/2022/04/11/valid-anagram/
IEEE
" » Valid Anagram." Stylus07 | Sciencx [Online]. Available: https://www.scien.cx/2022/04/11/valid-anagram/. [Accessed: ]
rf:citation
» Valid Anagram | Stylus07 | Sciencx | https://www.scien.cx/2022/04/11/valid-anagram/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.