alternative solution to anagram algo question

54 Views Asked by At

I've pasted the practice problem I'm solving as a photo below. I have one answer that works right, but I tried switching it up and I'm not sure why the alternative answer doesn't work. Would appreciate any explanations, thanks!

enter image description here

my solution that works

var string1 = "somethingb"
var string2 = "omesnigthr"

function validAn(string1,string2)
{
    let obj1 = {}
    let obj2 = {}

    if (string1.length !== string2.length){
        return false
    }
    for(let char of string1){ 
        obj1[char]= (obj1[char] || 0) + 1
    }
    for(let char of string2){
        obj2[char]= (obj2[char] || 0) + 1
    }
    for(var val in obj1){
        if(!(val in obj2)){
            return false
        }
        if(obj2[val] !== obj1[val]){
            return false
        }
    }
 return true
}

my solution that doesn't work

var string1 = "somethingb"
var string2 = "omesnigthr"

function validAn(string1,string2)
{
    let obj1 = {}
    let obj2 = {}

    if (string1.length !== string2.length){
        return false
    }
    for(let char of string1){ 
        obj1[char]= (obj1[char] || 0) + 1
    }
    for(let char of string2){
        obj2[char]= (obj2[char] || 0) + 1
    }
    for(var val in obj1){
        if(val in obj2) && (obj2[val] == obj1[val])){
            return true
        }
    }
return true
}

1

There are 1 best solutions below

0
On

In your second solution that doesn't work, you always return true. In the third for loop, you should check if both objects have the key with same value, and if not return false :

var string1 = "somethingb"
var string2 = "omesnigthr"

function validAn(string1,string2)
{
    let obj1 = {}
    let obj2 = {}

    if (string1.length !== string2.length){
        return false
    }
    for(let char of string1){ 
        obj1[char]= (obj1[char] || 0) + 1
    }
    for(let char of string2){
        obj2[char]= (obj2[char] || 0) + 1
    }
    for(var val in obj1){
        if(!(val in obj2) || (obj2[val] !== obj1[val])){
            return false
        }
    }
return true
}

console.log(validAn(string1, string2));