242. Valid Anagram

0

Table of Contents

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 1:Input: s = “anagram”, t = “nagaram” Output: true

Example 2:Input: s = “rat”, t = “car” Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solution

First attempt : (Non optimized)

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    const sset = s.split("");
    const tset = t.split("");
    if(s.length == t.length){
        for(let i = 0 ; i < sset.length; i++){
            let value =sset[i];
            if(tset.includes(value)){
                let index = tset.indexOf(value);
                tset.splice(index,1)
            }
            else{
                return false;
            }
        }
    }
    else{
        return false;
    }
    return true
};

After giving it a second attempt I tried optimizing it further and here is what I have done so far :

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    let ss = s.split("");
    let tt = t.split("");
    const dict = {}
    if(s.length == t.length){
        for(let i = 0 ; i < ss.length; i++){
            if(dict[ss[i]]){
                dict[ss[i]]++;
            }
            else{
                dict[ss[i]] = 1;
            }
        }
        for(let y = 0 ; y < tt.length; y++){
            if(dict[tt[y]]){
                dict[tt[y]]--;
            }
            else{
                return false;
            }
        }
    }
    else{
        return false;
    }
    return true
};

Leave a Comment

Skip to content