javascriptanagram

LeetCode's Valid Anagram challenge is not passing in all test cases but it works fine in my editor, why?


I tested my code on an online editor and it worked fine with all examples I tested, but it fails when I submit it to LeetCode. Why?

LeetCode submission result:

Wrong Answer 
24 / 38 testcases passed
Input
s = "a"
t = "a"
Output: false
Expected: true

The Leetcode's results show that my code returned "false", but if I run the same example on my editor, it works correctly returning "true" enter image description here

enter image description here

My code:

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */

let readedIndices = []
function checkReadedIndices(indice){
    let res = false
    for(let i=0; i<readedIndices.length; i++){
        if(indice == readedIndices[i]){
            res = true
        }
    }
    return res
}

var isAnagram = function(s, t) {
    let result = false
    if(s.length !== t.length)
        return result
    for(let i=0; i < s.length; i++){
        for(let n=0; n < t.length; n++){
            if(s[i] === t[n]){
                if(checkReadedIndices(n) === false){
                    readedIndices.push(n)
                    break
                }
            }
        }
    }
    if(readedIndices.length === s.length)
        result = true

    return result
};
//console.log(isAnagram("a", "a"))

Solution

  • The issue is that you're relying on global state with the readedIndices array. But the isAnagram function may be called multiple times with distinct inputs during the same run of the program. One way to fix this is to define both readedIndices and checkReadedIndices inside the isAnagram function (at the top).

    After fixing the logic, your function still won't be able to pass because it is too inefficient. Some better ways to solve the problem include sorting both strings (as arrays of characters) before comparing or counting the frequency of every letter in both strings and ensuring that all frequencies are equal.

    The sorting method relies on the fact that anagrams contain exactly the same characters, so they must be the exact same after sorting.

    return [...s].sort().join('') === [...t].sort().join('');