Anamika Singh
Anamika Singh

Reputation: 151

Anagram Javascript

Question with below code. If I'm decreasing the object value and when it comes to zero how it is satisfying this condition if(!obj1[letter]) because letter still exist in obj, its value is just going down.

function validAnagram(a, b){
if(a.length !== b.length){
    return false;
}
if(a.length === 0 && b.length === 0 ){
    return true;
}
    let obj1 = {};

  // add whatever parameters you deem necessary - good luck!
    for(let i= 0; i<a.length; i++){
        if(obj1[a[i]]>0){
            obj1[a[i]]++
        }else{
                   obj1[a[i]] = 1;
        }
 

        
    }
    for(let i =0; i<b.length; i++){
        let letter = b[i];
        if(!obj1[letter]){
            return false
        } else {
            obj1[letter]--
        }
    }
    return true;
}



validAnagram('aza', 'zaz')

Upvotes: 2

Views: 132

Answers (1)

user1984
user1984

Reputation: 6818

There are 3 cases for obj1[letter]:

  1. letter does not exists in obj1, in which case it evaluates to undefined.
  2. letter exists in obj1 and the value is none-zero.
  3. letter exists in obj1 and the value is zero.

Case two is obvious. The letter exists and the value is greater than zero, so it will me decremented by one.

Case one and three are so called falsy values in JavaScript and negating them with ! converts them to true, which makes sense. If the letter does not exist or is already exhausted, hence the value zero, it isn't a proper anagram.

In other words, the value won't go down further than zero. It will be caught on zero and the algorithm returns false.

Upvotes: 1

Related Questions