Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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')
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!