• + 1 comment

    My Java solution:

    public static int anagram(String s) {
            if (s.length() % 2 != 0) return -1; // If length is odd, return -1
    
            int[] frequency = new int[26]; // Array for character frequencies
    
            int mid = s.length() / 2;
            for (int i = 0; i < mid; i++) {
                frequency[s.charAt(i) - 'a']++;  // Count chars in first half
                frequency[s.charAt(i + mid) - 'a']--; // Subtract chars in second half
            }
    
            int changes = 0;
            for (int count : frequency) {
                if (count > 0) changes += count; // Count excess chars that need replacement
            }
    
            return changes;
        }