Java Anagrams

  • + 0 comments

    A bit of an odd solution, but the use of primes allows for a mathematic approach that doesn't require sorting and only requires traversing the arrays a single time. Not meaningfully better than storing an int in the index of the char value, but fun!

        static boolean isAnagram(String a, String b) {
            // Complete the function
            
            if(a.length() != b.length()) {
                return false;
            }
            
            a = a.toLowerCase();
            b = b.toLowerCase();
            
            int[] lookupArr = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
            int total = 0;
            
            for(int i = 0; i < a.length(); i++) {
                total += lookupArr[a.charAt(i) - 97];
                total -= lookupArr[b.charAt(i) - 97];
            }
            
            if(total == 0) {
                return true;
            }
            return false;
        }