Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Making Anagrams Problem Solution

HackerRank Making Anagrams Problem Solution

Posted on April 28, 2023May 6, 2023 By Yashwant Parihar No Comments on HackerRank Making Anagrams Problem Solution

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

Table of Contents

  • Making Anagrams C Solution
  • Making Anagrams C++ Solution
  • Making Anagrams C Sharp Solution
  • Making Anagrams Java Solution
  • Making Anagrams JavaScript Solution
  • Making Anagrams Python 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 Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Anagram Problem Solution
Next Post: HackerRank Game of Thrones – I Problem Solution

Related Posts

HackerRank Highest Value Palindrome Problem Solution HackerRank Highest Value Palindrome Solution c
HackerRank Count Strings Problem Solution HackerRank Count Strings Problem Solution c
HackerRank Minimum MST Graph Problem Solution HackerRank Minimum MST Graph Solution c
HackerRank Caesar Cipher Problem Solution HackerRank Caesar Cipher Problem Solution c
HackerRank Jogging Cats Problem Solution HackerRank Jogging Cats Problem Solution c
HackerRank Prim's (MST) : Special Subtree Problem Solution HackerRank Prim’s (MST) : Special Subtree c

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme