Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Making Anagrams Problem Solution

Yashwant Parihar, April 28, 2023May 6, 2023

In this post, we will solve HackerRank Making Anagrams Problem Solution.

We consider two strings to be anagrams of each other if the first string’s letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
Alice is taking a cryptography class and finding anagrams to be very useful. She decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?
Given two strings, $1 and $2, that may not be of the same length, determine the minimum number of character deletions required to make $1 and $2 anagrams. Any characters can be deleted from either of the strings.
Example.
s1 = abc
s2 = amnop
The only characters that match are the a’s so we have to remove bc from $1 and mnop from $2 for a total of 6 deletions.

Function Description

Complete the makingAnagrams function in the editor below.

makingAnagrams has the following parameter(s):

  • string s1: a string
  • string s2: a string

Returns

  • int: the minimum number of deletions needed

Input Format

The first line contains a single string, s1.
The second line contains a single string, s2.

Sample Input

cde
abc

Sample Output

4

Explanation

Delete the following characters from our two strings to turn them into anagrams:

  1. Remove d and e from cde to get c.
  2. Remove a and b from abc to get c.

 4 characters have to be deleted to make both strings anagrams.

HackerRank Making Anagrams Problem Solution
HackerRank Making Anagrams Problem Solution

Making Anagrams C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int a[26];
    int b[26];
    int i;
    
    for (i = 0; i < 26; i++) {
        a[i] = b[i] = 0;
    }
    
    char c[10000];
    char d[10000];
    
    scanf ("%s", c);
    scanf ("%s", d);
    
    for (i = 0; c[i]; i++) {
        a[c[i] - 'a']++;
    }
    
    for (i = 0; d[i]; i++) {
        b[d[i] - 'a']++;
    }
    
    int count = 0;
    
    for (i = 0; i < 26; i++) {
        count += abs(a[i] - b[i]);
    }
    
    printf ("%d\n", count);
    
    return 0;
}

Making Anagrams C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    std::string a; std::cin >> a;
    std::string b; std::cin >> b;
    int freq[26] = {0};
    for (char c : a) {
        freq[c - 'a'] += 1;
    }
    for (char c : b) {
        freq[c - 'a'] -= 1;
    }
    int mismatches = 0;
    for (int f : freq) {
        if (f < 0)
            mismatches -= f;
        else
            mismatches += f;
    }
    std::cout << mismatches << std::endl;
    return 0;
}

Making Anagrams C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;

class Solution {
    static void Main(String[] args) {
        var firstWordLetters = Console.ReadLine().ToCharArray().GroupBy(e=>e).ToDictionary(e=>e.Key, e=>e.Count());
        var secondWordLetters = Console.ReadLine().ToCharArray().GroupBy(e=>e).ToDictionary(e=>e.Key, e=>e.Count());
        
        var allLetters = firstWordLetters.Keys.Concat(secondWordLetters.Keys).Distinct();
        
        var count=0;
        foreach(var letter in allLetters)
        {
            if (firstWordLetters.ContainsKey(letter))
            {
                if (secondWordLetters.ContainsKey(letter))
                {
                    count += Math.Abs(firstWordLetters[letter] -secondWordLetters[letter]);     
                }
                else
                    count += firstWordLetters[letter]; 
            }
            else
                count+= secondWordLetters[letter];
        }
        Console.WriteLine(count);
    }
}

Making Anagrams Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'makingAnagrams' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING s1
     *  2. STRING s2
     */

    public static int makingAnagrams(String s1, String s2) {
    // Write your code here
        int[] freq = new int[26];
        s1.chars().forEach((c) -> { freq[c-97]++; });
        s2.chars().forEach((c) -> { freq[c-97]--; });
        return Arrays.stream(freq).map(Math::abs).sum();
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s1 = bufferedReader.readLine();

        String s2 = bufferedReader.readLine();

        int result = Result.makingAnagrams(s1, s2);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Making Anagrams JavaScript Solution

function processData(input) {
    input = input.split('\n');
    var A = JSON.stringify(input[0]);
    var B = JSON.stringify(input[1]);
    A = A.split('');
    B = B.split('');
    
    //console.log(A);
    //console.log(B);   
    
    for(var i = 0; i<A.length; i++){
        for(var j = 0; j<B.length; j++){
            if(A[i] === B[j]){
                A.splice(i,1);
                B.splice(j,1);
                i--;
                break;
            }
        }
    }
    //console.log(A);
    //console.log(B);
    
    console.log(A.length+B.length);
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Making Anagrams Python Solution

d1 = dict()
d2 = dict()
s1 = input()
s2 = input()
for c in s1:
    if c in d1:
        d1[c] += 1
    else:
        d1[c] = 1
for c in s2:
    if c in d2:
        d2[c] += 1
    else:
        d2[c] = 1
count = 0
for c, v in d1.items():
    if c in d2:
        count += abs(d1[c]-d2[c])
        d2[c] = 0
    else:
        count += d1[c]
for c,v in d2.items():
    if v:
        count += v
print(count)

Other Solutions

  • HackerRank Game of Thrones – I Problem Solution
  • HackerRank Two Strings Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes