Strings: Making Anagrams

  • + 0 comments

    Java Solution using int array for 26 English letters:

    public static int makeAnagram(String a, String b) {
        // Since there are only 26 lowercase English letters
        int[] charCount = new int[26]; 
        int deleteCount = 0;
    
        // Count frequency of each character in string 'a'
        for (char c : a.toCharArray()) {
            charCount[c - 'a']++;
        }
    
        // Adjust frequency based on characters in string 'b'
        for (char c : b.toCharArray()) {
            charCount[c - 'a']--;
        }
    
        // Sum up the absolute differences to calculate deletions
        for (int count : charCount) {
            deleteCount += Math.abs(count);
        }
    
        return deleteCount;
    }