-3

Why doesn't this solution work for finding valid anagram?

26/36 test cases get passed in LeetCode.

class Solution {
    public boolean isAnagram(String s, String t) {
        
        int sASCII = 0, tASCII = 0;
        
        if(s.length() != t.length()) {return false;}
        else{
            for(int i = 0 ; i < s.length(); i++){
                
       
                sASCII += (int)s.charAt(i);
                tASCII += (int)t.charAt(i);
                
                
            }
        }
        if(sASCII == tASCII){
            return true;
        }
        return false;
    }
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 3
    Do you consider `"ad"` and `"bc"` to be anagrams? because they are according to your code – UnholySheep Apr 26 '22 at 21:54
  • Sorry, but the algorithm you chose has nothing to do with finding anagrams. You need to rethink your approach. – Jim Garrison Apr 26 '22 at 22:06
  • Though it might be a useful way to pre-test for "not an anagram", Consider: if most test cases are not anagrams, this could quickly reject them in O(n) time. Only if the sums are equal do you have to sort and compare. (Measure before concluding this is a performance win). – passer-by Apr 26 '22 at 22:33

1 Answers1

0

The sums tASCII and sASCII can be equal even if the numbers are not anagrams. Let's say that you can get the number 100 by adding 60+40, but you can also get it by adding 70+30, so i recommend to use a HashMap to note every occurence of every letter or to sort the strings as arrays of chars and then compare them.