In this post, we will solve Making Anagrams HackerRank Solution. This problem (Making Anagrams) is a part of HackerRank Problem Solving series.
Solution – Making Anagrams – HackerRank Solution
C++
#include <cmath> #include <cstring> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Given two strings, finds the minimum number of character deletions required to make the two strings anagrams. int main() { char s1[10010],s2[10010]; cin>>s1>>s2; int a[26]={0}; for(int i=0;i<strlen(s1);i++) a[s1[i]-'a']++; for(int i=0;i<strlen(s2);i++) a[s2[i]-'a']--; long long int ans = 0; for(int i=0;i<26;i++) ans += abs(a[i]); cout<<ans<<endl; return 0; }
Python
#!/bin/python3 import sys from collections import Counter def makingAnagrams(s1, s2): res = 0 cnt1 = Counter(s1) cnt2 = Counter(s2) cnt3 = {} for let, val in cnt1.items(): cnt3[let] = abs(val - cnt2[let]) for let, val in cnt2.items(): cnt3[let] = abs(val - cnt1[let]) for el in cnt3.values(): res += el return res s1 = input().strip() s2 = input().strip() result = makingAnagrams(s1, s2) print(result)
Java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Solution { private static final Scanner scanner = new Scanner(System.in); // Complete the makeAnagram function below. static int makeAnagram(String a, String b) { Map<Integer, Integer> map = new HashMap<>(); a.chars().forEach(c -> map.put(c, map.getOrDefault(c, 0) + 1)); b.chars().forEach(c -> map.put(c, map.getOrDefault(c, 0) - 1)); return map.values().stream().reduce(0, (subtotal, value) -> subtotal + Math.abs(value)); } public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String a = scanner.nextLine(); String b = scanner.nextLine(); int res = makeAnagram(a, b); bufferedWriter.write(String.valueOf(res)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
Note: This problem (Making Anagrams) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.