Check if two strings are k-anagrams or not | Practice | GeeksforGeeks

Given two strings of lowercase alphabets and a value K, your task is to complete the given function which tells if  two strings are K-anagrams of each other or not.
Two strings are called K-anagrams if both of the below 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.
Example:
Input:
str1 = "fodr", str2="gork"
k = 2
Output:
1
Explanation: Can change fd to gk
Your Task:
Since this is a function problem, you don't need to take any input. Just complete the given function areKAnagrams that returns true if the strings can be turned into K-anagrams, else return false.
Constraints:
1 ≤ length of String ≤ 105
1 ≤ K ≤ length of String
0
gauravsingh564 days ago
class Solution {   boolean areKAnagrams(String s1, String s2, int k) {       // code here       int count=0;       if(s1.length()!=s2.length()) return false;              Map<Character,Integer> map=new HashMap<>();       for(int i=0;i<s1.length();i++)           map.put(s1.charAt(i),map.getOrDefault(s1.charAt(i),0)+1);       for(int i=0;i<s2.length();i++){           if(map.getOrDefault(s2.charAt(i),0)>0){               map.put(s2.charAt(i),map.get(s2.charAt(i))-1);           }       }              for(char c: map.keySet()){          count+=map.get(c);      }              if(count>k) return false;       return true;   }}
0
geminicode2 weeks ago
My approach in python using dictionary
def areKAnagrams(self, str1, str2, k):
        # code here
        if len(str1) != len(str2):
            return 0
        hmap1 = {}
        hmap2 = {}
        for i in range(97,123):
            hmap1[chr(i)] = 0
            hmap2[chr(i)] = 0
        for i in range(len(str1)):
            hmap1[str1[i]] += 1
        for i in range(len(str2)):
            hmap2[str2[i]] += 1
        count = 0
        for key,val in hmap1.items():
            #print(val,hmap2[key])
            if val - hmap2[key] > 0:
                count += val-hmap2[key]
        #print(count)
        if count <= k:
            return 1
        else:
            return 0
0
ameenul88082 weeks ago
C++ simple solution
bool areKAnagrams(string str1, string str2, int k) {
       if(str1.length()!=str2.length()) return false;
       unordered_map<char, int> mp;
       for (int i =0;i<str1.length();i++){
          mp[str1[i]]++;
       }

       for(int i=0;i<str2.length();i++){
           if(!(mp[str2[i]])){
           if(k==0){
              return false;
           }
           k--;
       }
       else{
          mp[str2[i]]--;
       }
   }
   return true;
  }
+1
radhesh1853 weeks ago
Simple CPP Solution:
const int MAX_CHAR = 26;
    bool areKAnagrams(string str1, string str2, int k) {
        // code here
        
       int n1=str1.length();
       int n2=str2.length();
       
       if(n1!=n2)
       {
           return false;
           
       }
     
      int arr1[MAX_CHAR]={0};
      int arr2[MAX_CHAR]={0};
      for(int i=0;i<n1;i++)
      {
          arr1[str1[i]-'a']++;
          arr2[str2[i]-'a']++;
      }
      int count=0;
      for(int i=0;i<MAX_CHAR;i++)
      {
          if(arr1[i]>arr2[i])
          {
              count+=abs(arr1[i]-arr2[i]);
          }
      }
      if(count<=k)
      {
          return true;
      }
      else{
          return false;
      }
    }
0
kalash4 weeks ago
c++ solution without using hash
class Solution {
  public:
    bool areKAnagrams(string str1, string str2, int k) {
        if(str1.size() != str2.size()){
            return false;
        }
        // int count = 0;
        bool flag = true;
        for(int i = 0; i < str1.size(); i++){
            for(int j = 0; j < str2.size(); j++){
                if(str1[i] == str2[j]){
                    str2.erase(str2.begin() + j);
                    break;
                }
            }
        }
        if(str2.size() <= k){
            return true;
        }
        return false;
        // code here
    }
};
+1
vrajeshmodi991 month ago
 bool areKAnagrams(string str1, string str2, int k) {
        if(str1.size()!= str2.size())return false;
        
        unordered_map<char,int>mp;
        for(int i=0;i<str2.size();i++){
            mp[str2[i]]++;
        }
        
        int rep=0;
        for(int i=0;i<str1.size();i++){
            if(!mp.count(str1[i])){
                rep++;
            }
            else{
                mp[str1[i]]--;
                if(mp[str1[i]]==0)mp.erase(str1[i]);
            }
            if(rep>k)return false;
        }
        return true;
    }
0
manasshresthafb1 month ago
Dart

var source = "abc";
  var target = "bca";
  int k = 2;

  var splittedSource = source.split("");
  var splittedTarget = target.split("");

  for (var element in List.from(splittedSource)) {
    if (splittedTarget.contains(element)) {
      splittedSource.remove(element);
      splittedTarget.remove(element);
    }
  }

  if ((splittedTarget.length + splittedSource.length) <= k) {
    print("Can ba anagrams");
  }
0
abhishekshrivastav19201 month ago
        if(str1.length() != str2.length())return false;
       unordered_map<char,int> FreqMap;
       
       for(int i = 0; i<str1.length(); i++){
           FreqMap[str1[i]]++;
       }
       
       for(int i = 0; i<str2.length() ; i++){
           if(FreqMap.find(str2[i])==FreqMap.end()){
               continue;
           }
           
           if(FreqMap[str2[i]]==1){
               FreqMap.erase(str2[i]);   
           }else{
               FreqMap[str2[i]]--;
           }
           
       }
       
       int BadElement = 0;
       
       for(auto &f : FreqMap){
           BadElement += f.second;
       }
       
       return BadElement > k ? false : true;
0
tyagipratap1112 months ago
// Simple java solution
boolean areKAnagrams(String s1, String s2, int k{
if (s1.length() != s2.length()) {
            return false;
        }

        HashMap<Character, Integer> map = new HashMap<>();
        int count = 0;
        for (int i = 0; i < s1.length(); i++)
            map.put(s1.charAt(i), map.containsKey(s1.charAt(i)) ? map.get(s1.charAt(i)) + 1 : 1);

        for (int i = 0; i < s2.length(); i++) {
            if (!map.containsKey(s2.charAt(i)))
                count++;
            else {
                map.put(s2.charAt(i), map.get(s2.charAt(i)) - 1);
                if (map.get(s2.charAt(i)) == 0)
                    map.remove(s2.charAt(i));
            }
        }
        if (count <= k)
            return true;
        return false;
        }
0
randhirmishra1019982 months ago
if(s1.length()!=s2.length()){       return false;   }   int[]count1=new int[256];   int[]count2=new int[256];      for(int i=0;i<s1.length();i++){       count1[s1.charAt(i)]++;       count2[s2.charAt(i)]++;   }   int count=0;   for(int i=0;i<count1.length;i++){       count+=Math.abs(count1[i]-count2[i]);   }   count=count/2;      if(count<=k){       return true;   }else{       return false;   }   
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.