Open in App
Not now

# Check if two strings are k-anagrams or not

• Difficulty Level : Easy
• Last Updated : 17 Jan, 2023

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.

Method 1:

Below is a solution to check if two strings are k-anagrams of each other or not.

1. Stores occurrence of all characters of both strings in separate count arrays.
2. Count number of different characters in both strings (in this if a string has 4 a and second has 3 ‘a’ then it will be also counted.
3. If count of different characters is less than or equal to k, then return true else false.

Implementation:

## C++

 // C++ program to check if two strings are k anagram // or not. #include using namespace std; const int MAX_CHAR = 26;   // Function to check that string is k-anagram or not bool arekAnagrams(string str1, string str2, int k) {     // If both strings are not of equal     // length then return false     int n = str1.length();     if (str2.length() != n)         return false;       int count1[MAX_CHAR] = {0};     int count2[MAX_CHAR] = {0};       // Store the occurrence of all characters     // in a hash_array     for (int i = 0; i < n; i++)         count1[str1[i]-'a']++;     for (int i = 0; i < n; i++)         count2[str2[i]-'a']++;            int count = 0;       // Count number of characters that are     // different in both strings     for (int i = 0; i < MAX_CHAR; i++)         if (count1[i] > count2[i])             count = count + abs(count1[i]-count2[i]);       // Return true if count is less than or     // equal to k     return (count <= k); }   // Driver code int main() {     string str1 = "anagram";     string str2 = "grammar";     int k = 2;     if (arekAnagrams(str1, str2, k))         cout << "Yes";     else         cout<< "No";     return 0; }

## Java

 // Java program to check if two strings are k anagram // or not. public class GFG {            static final int MAX_CHAR = 26;       // Function to check that string is k-anagram or not     static boolean arekAnagrams(String str1, String str2,                                                  int k)     {         // If both strings are not of equal         // length then return false         int n = str1.length();         if (str2.length() != n)             return false;           int[] count1 = new int[MAX_CHAR];         int[] count2 = new int[MAX_CHAR];         int count = 0;                  // Store the occurrence of all characters         // in a hash_array         for (int i = 0; i < n; i++)             count1[str1.charAt(i) - 'a']++;         for (int i = 0; i < n; i++)             count2[str2.charAt(i) - 'a']++;           // Count number of characters that are         // different in both strings         for (int i = 0; i < MAX_CHAR; i++)             if (count1[i] > count2[i])                 count = count + Math.abs(count1[i] -                                           count2[i]);           // Return true if count is less than or         // equal to k         return (count <= k);     }       // Driver code     public static void main(String args[])     {         String str1 = "anagram";         String str2 = "grammar";         int k = 2;         if (arekAnagrams(str1, str2, k))             System.out.println("Yes");         else             System.out.println("No");     } } // This code is contributed by Sumit Ghosh

## Python3

 # Python3 program to check if two # strings are k anagram or not. MAX_CHAR = 26   # Function to check that is # k-anagram or not def arekAnagrams(str1, str2, k) :       # If both strings are not of equal     # length then return false     n = len(str1)     if (len(str2)!= n) :         return False       count1 = [0] * MAX_CHAR     count2 = [0] * MAX_CHAR       # Store the occurrence of all     # characters in a hash_array     for i in range(n):         count1[ord(str1[i]) -                ord('a')] += 1     for i in range(n):         count2[ord(str2[i]) -                ord('a')] += 1               count = 0       # Count number of characters that     # are different in both strings     for i in range(MAX_CHAR):         if (count1[i] > count2[i]) :             count = count + abs(count1[i] -                                 count2[i])       # Return true if count is less     # than or equal to k     return (count <= k)   # Driver Code if __name__ == '__main__':     str1 = "anagram"     str2 = "grammar"     k = 2     if (arekAnagrams(str1, str2, k)):         print("Yes")     else:         print("No")   # This code is contributed # by SHUBHAMSINGH10

## C#

 // C# program to check if two // strings are k anagram or not. using System; class GFG {           static int MAX_CHAR = 26;       // Function to check that     // string is k-anagram or not     static bool arekAnagrams(string str1,                              string str2,                                       int k)     {                   // If both strings are not of equal         // length then return false         int n = str1.Length;         if (str2.Length != n)             return false;           int[] count1 = new int[MAX_CHAR];         int[] count2 = new int[MAX_CHAR];         int count = 0;                   // Store the occurrence         // of all characters         // in a hash_array         for (int i = 0; i < n; i++)             count1[str1[i] - 'a']++;         for (int i = 0; i < n; i++)             count2[str2[i] - 'a']++;           // Count number of characters that are         // different in both strings         for (int i = 0; i < MAX_CHAR; i++)             if (count1[i] > count2[i])                 count = count + Math.Abs(count1[i] -                                          count2[i]);           // Return true if count is         // less than or equal to k         return (count <= k);     }       // Driver code     public static void Main()     {         string str1 = "anagram";         string str2 = "grammar";         int k = 2;         if (arekAnagrams(str1, str2, k))             Console.Write("Yes");         else             Console.Write("No");     } } // This code is contributed by nitin mittal.

## PHP

 \$count2[\$i])             \$count = \$count + abs(\$count1[\$i] -                                   \$count2[\$i]);       // Return true if count is     // less than or equal to k     return (\$count <= \$k); }   // Driver Code \$str1 = "anagram"; \$str2 = "grammar"; \$k = 2; if (arekAnagrams(\$str1, \$str2, \$k))     echo "Yes"; else     echo "No";   // This code is contributed by m_kit ?>

## Javascript



Output

Yes

Time complexity: O(n)
Auxiliary Space: O(1)

Method 2: We can optimize above solution. Here we use only one count array to store counts of characters in str1. We traverse str2 and decrement occurrence of every character in count array that is present in str2. If we find a character that is not there in str1, we increment count of different characters. If count of different character become more than k, we return false.

Implementation:

## C++

 // Optimized C++ program to check if two strings // are k anagram or not. #include using namespace std;   const int MAX_CHAR = 26;   // Function to check if str1 and str2 are k-anagram // or not bool areKAnagrams(string str1, string str2, int k) {     // If both strings are not of equal     // length then return false     int n = str1.length();     if (str2.length() != n)         return false;       int hash_str1[MAX_CHAR] = {0};       // Store the occurrence of all characters     // in a hash_array     for (int i = 0; i < n ; i++)         hash_str1[str1[i]-'a']++;       // Store the occurrence of all characters     // in a hash_array     int count = 0;     for (int i = 0; i < n ; i++)     {         if (hash_str1[str2[i]-'a'] > 0)             hash_str1[str2[i]-'a']--;         else             count++;           if (count > k)             return false;     }       // Return true if count is less than or     // equal to k     return true; }   // Driver code int main() {     string str1 = "fodr";     string str2 = "gork";     int k = 2;     if (areKAnagrams(str1, str2, k) == true)         cout << "Yes";     else         cout << "No";     return 0; }

## Java

 // Optimized Java program to check if two strings // are k anagram or not. public class GFG {           static final int MAX_CHAR = 26;            // Function to check if str1 and str2 are k-anagram     // or not     static boolean areKAnagrams(String str1, String str2,                                                   int k)     {         // If both strings are not of equal         // length then return false         int n = str1.length();         if (str2.length() != n)             return false;                int[] hash_str1 = new int[MAX_CHAR];                // Store the occurrence of all characters         // in a hash_array         for (int i = 0; i < n ; i++)             hash_str1[str1.charAt(i)-'a']++;                // Store the occurrence of all characters         // in a hash_array         int count = 0;         for (int i = 0; i < n ; i++)         {             if (hash_str1[str2.charAt(i)-'a'] > 0)                 hash_str1[str2.charAt(i)-'a']--;             else                 count++;                    if (count > k)                 return false;         }                // Return true if count is less than or         // equal to k         return true;     }            // Driver code     public static void main(String args[])     {         String str1 = "fodr";         String str2 = "gork";         int k = 2;         if (areKAnagrams(str1, str2, k) == true)             System.out.println("Yes");         else             System.out.println("No");     } } // This code is contributed by Sumit Ghosh

## Python3

 # Optimized Python3 program # to check if two strings # are k anagram or not. MAX_CHAR = 26;   # Function to check if str1 # and str2 are k-anagram or not def areKAnagrams(str1, str2, k):     # If both strings are     # not of equal length     # then return false       n = len(str1);     if (len(str2) != n):         return False;       hash_str1 = [0]*(MAX_CHAR);       # Store the occurrence of     # all characters in a hash_array     for i in range(n):         hash_str1[ord(str1[i]) - ord('a')]+=1;       # Store the occurrence of all     # characters in a hash_array     count = 0;     for i in range(n):         if (hash_str1[ord(str2[i]) - ord('a')] > 0):             hash_str1[ord(str2[i]) - ord('a')]-=1;         else:             count+=1;           if (count > k):             return False;       # Return true if count is     # less than or equal to k     return True;   # Driver code str1 = "fodr"; str2 = "gork"; k = 2; if (areKAnagrams(str1, str2, k) == True):     print("Yes"); else:     print("No");           # This code is contributed by mits

## C#

 // Optimized C# program to check if two strings // are k anagram or not. using System;    class GFG {           static  int MAX_CHAR = 26;           // Function to check if str1 and str2 are k-anagram     // or not     static bool areKAnagrams(String str1, String str2,                                                 int k)     {         // If both strings are not of equal         // [i] then return false         int n = str1.Length;         if (str2.Length != n)             return false;               int[] hash_str1 = new int[MAX_CHAR];               // Store the occurrence of all characters         // in a hash_array         for (int i = 0; i < n ; i++)             hash_str1[str1[i]-'a']++;               // Store the occurrence of all characters         // in a hash_array         int count = 0;         for (int i = 0; i < n ; i++)         {             if (hash_str1[str2[i]-'a'] > 0)                 hash_str1[str2[i]-'a']--;             else                 count++;                   if (count > k)                 return false;         }               // Return true if count is less than or         // equal to k         return true;     }           // Driver code      static void Main()     {         String str1 = "fodr";         String str2 = "gork";         int k = 2;           if (areKAnagrams(str1, str2, k) == true)             Console.Write("Yes");         else             Console.Write("No");     } } // This code is contributed by Anuj_67

## PHP

 0)             \$hash_str1[\$str2[\$i] - 'a']--;         else             \$count++;           if (\$count > \$k)             return false;     }       // Return true if count is     // less than or equal to k     return true; }   // Driver code \$str1 = "fodr"; \$str2 = "gork"; \$k = 2; if (areKAnagrams(\$str1, \$str2, \$k) == true)     echo "Yes"; else     echo "No";           // This code is contributed by ajit ?>

## Javascript



Output

Yes

Time complexity: O(n)
Auxiliary Space: O(1)

This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up
Related Articles