HackerRank Making Anagrams Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Making Anagrams Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

Making Anagrams problem solution
Making Anagrams problem solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Making Anagrams

Task

We consider two strings to be anagrams of each other if the first strings 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, s1 and s2, that may not be of the same length, determine the minimum number of character deletions required to make s1 and s2 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 s1 and mnop from s2 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.

Constraints

  • 1 <= |s1|, |s2| <= 104
  • It is guaranteed that s1 and s2 consist of lowercase English letters, ascii[az].

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.

 characters have to be deleted to make both strings anagrams.

HackerRank Making Anagrams Solution

Making Anagrams Solution in C

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

int main() {

    char str1[20000];
    char str2[20000];
    
    scanf("%s", str1);
    scanf("%s", str2);
    
    int n1 = strlen(str1);
    int n2 = strlen(str2);
    
int i, j;
    char s1[26] = {0};
   
    for (i = 0; i < n1; ++i) {
        s1[str1[i] - 97] += 1;
    }
    
    for (i = 0; i < n2; ++i) {
        s1[str2[i] - 97] -= 1;
    }
    int count = 0;
    for (i = 0; i < 26; ++i) {
        count += abs(s1[i]);
    }
    printf("%d\n", count);
    return 0;
}

Making Anagrams Solution in Cpp

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


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;
}

Making Anagrams Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. 
        Print output to STDOUT. Your class should be named Solution. */
        
        Scanner in = new Scanner(System.in);
        String src = (in.nextLine());
        String tar = in.nextLine();
        int length = 0;       
		Map<Character, Integer> an= new HashMap <Character, Integer>();	
		
		for ( int i=0; i< src.length(); i++){			
			char c = src.charAt(i);			
			if (an.containsKey(c) )			
				an.put(c, an.get(c)+1);
			else
				an.put(c, 1);			
		}
		
		for ( int j=0; j< tar.length(); j++){			
			char c = tar.charAt(j);					
			if (an.containsKey(c) && an.get(c)!= 0 ) {
				an.put(c,an.get(c) -1);
                length+=2;
            }
            
		}	
        
        System.out.println(src.length() + tar.length()- length );
            
      }
    
}

Making Anagrams Solution in Python

w1=raw_input()
w2=raw_input()

total=0
for letter in "abcdefghijklmnopqrstuvwxyz":
    total+=abs(w1.count(letter)-w2.count(letter))
print total

Making Anagrams Solution using JavaScript

  var processData, solve;

  processData = function(input) {
    var A, B, answer, _ref;
    _ref = input.split('\n'), A = _ref[0], B = _ref[1];
    answer = solve(A, B);
    console.log(answer);
    return answer;
  };

  solve = function(A, B) {
    var hash, i, key, sum, _i, _j, _ref, _ref1;
    hash = {};
    A = A.split('');
    for (i = _i = 0, _ref = A.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
      if (A[i] in hash) {
        hash[A[i]] += 1;
      } else {
        hash[A[i]] = 1;
      }
    }
    for (i = _j = 0, _ref1 = B.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
      if (B[i] in hash) {
        hash[B[i]] -= 1;
      } else {
        hash[B[i]] = -1;
      }
    }
    sum = 0;
    for (key in hash) {
      sum += Math.abs(hash[key]);
    }
    return sum;
  };

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 Solution in Scala

import java.util.Scanner

object Solution {

  def main(args: Array[String]) {

    val sc = new Scanner(System.in);

    val n1 = sc.nextLine().toList.groupBy(e => e).map(e => (e._1, e._2.size)).withDefaultValue(0)
    val n2 = sc.nextLine().toList.groupBy(e => e).map(e => (e._1, e._2.size)).withDefaultValue(0)
    var minDel = 0

    for (key <- n1.keySet ++ n2.keySet) {
      minDel += Math.max(n1(key), n2(key)) - Math.min(n1(key), n2(key))
    }

    System.out.println(minDel)

  }

}

Making Anagrams Solution in Pascal

{$H+}
uses math;
const
 tfi='';
 tfo='';

var
 fi,fo:text;
 n,t:longint;
 a,b:string;
 d1,d2:array['a'..'z'] of longint;

procedure nhap;
 var i:longint;
 begin
     readln(fi,a);
     readln(fi,b);
 end;

procedure process;
 var i,j,tg:longint;
     ch:char;
 begin
     for i:=1 to length(a) do inc(d1[a[i]]);
     for i:=1 to length(b) do inc(d2[b[i]]);
     for ch:='a' to 'z' do
      t:=t+max(d1[ch],d2[ch])-min(d1[ch],d2[ch]);
     writeln(fo,t); 
 end;

BEGIN
    assign(fi,tfi);reset(fi);
    assign(fo,tfo);rewrite(fo);
      nhap;
      process;
    close(fi);close(fo);
END.

Disclaimer: This problem (Making Anagrams) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment