Check if two strings are k-anagrams or not

Given two strings of lowercase alphabets and a value k, the task is to find if two strings are K-anagrams of each other or not.

Two strings are called k-anagrams if following two conditions are true.

  1. Both have same number of characters.

  2. Two strings can become anagram by changing at most k characters in a string.

Examples :

Input:  str1 = "anagram" , str2 = "grammar" , k = 3
Output:  Yes
Explanation: We can update maximum 3 values and 
it can be done in changing only 'r' to 'n' 
and 'm' to 'a' in str2.

Input:  str1 = "geeks", str2 = "eggkf", k = 1
Output:  No
Explanation: We can update or modify only 1 
value but there is a need of modifying 2 characters. 
i.e. g and f in str 2.
class Solution {
    public boolean arekAnagrams(String str1, String str2, int k) {
        if (str1.length() != str2.length)
            return false;
        int n = str1.length();

        int[] count1 = new int[26];
        int[] count2 = new int[26];
        int count = 0;

        for (int i = 0; i < n; i++)
            count1[str1.charAt(i) - 'a']++;
        for (int i = 0; i < n; i++)
            count2[str2.charAt(i) - 'a']++;

        for (int i = 0; i < 26; i++)
            count = count + Math.abs(count1[i] - count2[i]);

        // Return true if count is less than or equal to k
        return (count / 2 <= k);
    }
}

Last updated