DEV Community

OlumideSamuel
OlumideSamuel

Posted on

Valid Anagram. (Javascript DSA Series)

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
  • Input: s = "anagram", t = "nagaram"
  • Output: true
  • Input: s = "rat", t = "car"
  • Output: false
  • Constraints
  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

Solution

There are two ways of solving this problem.

Method One

/**
 * Since t is compared to s,
 * convert all to lowercase,
 * sort t and s, 
 * if t is exactly equal to s, then it is an anagram, else it isn't
 * Runtime O(n)
 */

// const s = "anagram";
// const t = "nagaram" 
const s = "rat", t = "car"
function anagram(s, t){
    const sortedS = s.split('').sort().join('');
    const sortedT = t.split('').sort().join('');
    if (sortedS === sortedT) return true;
    return false;
}
Enter fullscreen mode Exit fullscreen mode

Method Two

Using Map

/**
 * Create a map object
 * For each char in S, add the first occurrence with a value of 1. For subsequent occurrence, increase the value by +1.
 * For each char in T, if it doesn't exist in map i.e undefined or value is <= 0, return false. If it does exist, do value -1, return true outside loop.
 * @param {*} s 
 * @param {*} t 
 */

function anagramTwo(s,t){
    // for our answer to be an anagram, the word must be rearranged, hence, if the length of the two words are not same, it is not an anagram.
    if(s.length !== t.length) return false;

    const map = {};
    for (let i of s) {
        if(map[i] !== undefined) {
            map[i]++
         } else map[i] = 1
    }

    for (let i of t){
        if (map[i] === undefined || map[i] <= 0) return false;
        map[i]--;
    }
    return true

}

console.log(anagramTwo("ab", "a"))
Enter fullscreen mode Exit fullscreen mode

If you find this helpful, like, share and bookmark. :)

Top comments (0)