DEV Community

Discussion on: A classic interview question

Collapse
 
stoiandan profile image
Stoian Dan • Edited

So with the sort function you have O(nlog(n)). Then how about this solution for O(n). You have a dictionary with the char as key, and counter (how many times char appeared) as value. You iterate with a for over both arrays at the same time (O(n)) and each char in the first string adds to that key, while the same char in the second string subtracts. In the end you want to have 0 for all keys:

function anagram(str1, str2){

    //Prepare a dictionary to count appearances

    const dict = {}
    const arr1 = str1.split('');
    const arr2 = str2.split('');

    // if lenght is different return false, think it's O(1)
    if(arr1.length != arr2.length) return false


    for(let i = 0; i < str1.length; ++i){
        // increase number for keys in arr1 and decrease for keys in arr 2
        // if the same, result should be 0 in the end
        if(dict[arr1[i]] != undefined){
            dict[arr1[i]] = 1
        }else{
            dict[arr1[i]] += 1
        }

        if(dict[arr2[i]] != undefined){
            dict[arr2[i]] = -1
        }else{
            dict[arr2[i]] -= 1
        }
    }

    // check the dict
    for(let key in dict){
        if(dict[key] != 0){
            return false;
        }
    }
    // if reatched, it means all keys are 0
    return true
}