HackerRank Anagram Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Anagram 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.

Anagram problem solution
Anagram 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 Anagram

Task

Two words are anagrams of one another if their letters can be rearranged to form the other word.

Given a string, split it into two contiguous substrings of equal length. Determine the minimum number of characters to change to make the two substrings into anagrams of one another.

Example

s = abccde

Break s into two parts: abc’ and ‘cde’. Note that all letters have been used, the substrings are contiguous and their lengths are equal. Now you can change ‘aand ‘b’ in the first substring to ‘d’ and ‘e’ to have ‘dec’ and ‘cde’ which are anagrams. Two changes were necessary.

Function Description

Complete the anagram function in the editor below.

anagram has the following parameter(s):

  • string s: a string

Returns

  • int: the minimum number of characters to change or -1.

Input Format

The first line will contain an integer, q, the number of test cases.
Each test case will contain a string s.

Constraints

  • 1 <= q <= 100
  • 1 <= |s| <= 104
  • s consists only of characters in the range ascii[a-z].

Sample Input

6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx

Sample Output

3
1
-1
2
0
1

Explanation

Test Case #01: We split s into two strings S1 =’aaaand S2 =’bbb’. We have to replace all three characters from the first string with ‘b’ to make the strings anagrams.

Test Case #02: You have to replace ‘a’ with ‘b, which will generate “bb”.

Test Case #03: It is not possible for two strings of unequal length to be anagrams of one another.

Test Case #04: We have to replace both the characters of first string (“mn”) to make it an anagram of the other one.

Test Case #05: S1 and S2 are already anagrams of one another.

Test Case #06: Here S1 = “xaxb” and S2 = “bbxx”. You must replace ‘a’ from S1 with ‘b’ so that S1 = “xbxb”.

HackerRank Anagram Solution

Anagram Solution in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<malloc.h>
#define lld long long int
#define llu long long unsigned int
int compare(const void * a, const void * b){return *(lld *)a-*(lld *)b;}
long long int readint() {long long int n=0,count=0,counti=0; char c;while(1){c=getchar_unlocked();if(c=='-')count=1;else if((c==' '||c=='\n'||c==EOF) && counti==1)break;else if(c>='0' && c<='9'){counti=1;n=(n<<3)+(n<<1)+c-'0';}}if(count==0)return n;else return -n;}
#define min(a,b)(a>b?b:a)
#define max(a,b)(a<b?b:a)
#define sort(arr,n) qsort(arr,n,sizeof(arr[0]),compare)
#define sd(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define su(n) scanf("%llu",&n)
#define rep(i,start,end) for(i=start; i<end; i++)
#define pdn(n) printf("%d\n",n)
#define pln(n) printf("%lld\n",n)
#define pun(n) printf("%llu\n",n)
#define pd(n) printf("%d",n)
#define pl(n) printf("%lld",n)
#define pu(n) printf("%llu",n)
#define pn printf("\n")
#define ps printf(" ")
int mod(int a)
{
    if(a>0)return a;
    else return -a;
}
int main()
{
    int t;
    char str[10009];
    sd(t);
    getchar();
    while(t--)
    {
        int ar[26]={},arr[26]={};
        scanf("%s",str);
        getchar();
        int len=strlen(str),i;
        if(len%2==0)
        {
            for(i=0; i<(len/2); i++)
                ar[str[i]-'a']++;
            for(i=(len/2); i<len; i++)
                arr[str[i]-'a']++;
            int ans=0;
            for(i=0; i<26; i++)
                ans+=mod(ar[i]-arr[i]);
            pdn(ans/2);
        }
        else
            printf("-1\n");
    }
    return 0;
}

Anagram Solution in Cpp

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define SZ(x) ((int)(x).size())
#define FOR(it,c) for ( __typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++ )
using namespace std;
#define N 10010
char s[N],sa[N],sb[N];
int main()
{
    int t;
    scanf("%d",&t);
    while ( t-- ) {
        scanf("%s",s);
        int n=strlen(s);
        if ( n%2!=0 ) {
            puts("-1");
            continue;
        }
        int cnt[26]={};
        for ( int i=0; i<n/2; i++ ) cnt[s[i]-'a']++;
        for ( int i=n/2; i<n; i++ ) cnt[s[i]-'a']--;
        int ans=0;
        for ( int i=0; i<26; i++ ) ans+=abs(cnt[i]);
        printf("%d\n",ans/2);
    }
    return 0;
}

Anagram Solution in Java

import java.io.*;
import java.util.*;

public class Solution {

	static void solve() throws IOException {
		int tests = nextInt();
		while (tests-- > 0) {
			String s = nextToken();
			int answer = solve(s);
			out.println(answer);
		}
	}

	private static int solve(String s) {
		if ((s.length() & 1) != 0) {
			return -1;
		}
		int k = s.length() >> 1;
		char[] c1 = s.substring(0, k).toCharArray();
		char[] c2 = s.substring(k, 2 * k).toCharArray();
		int[] cnt1 = get(c1);
		int[] cnt2 = get(c2);
		int result = 0;
		for (int i = 0; i < 256; i++) {
			result += Math.abs(cnt1[i] - cnt2[i]);
		}

		return result >> 1;
	}

	private static int[] get(char[] c1) {
		int[] ret = new int[256];
		for (char cc : c1) {
			++ret[cc];
		}
		return ret;
	}

	static BufferedReader br;
	static StringTokenizer st;
	static PrintWriter out;

	public static void main(String[] args) throws IOException {
		InputStream input = System.in;
		PrintStream output = System.out;
		File file = new File("a.in");
		if (file.exists() && file.canRead()) {
			input = new FileInputStream(file);
		}
		br = new BufferedReader(new InputStreamReader(input));
		out = new PrintWriter(output);
		solve();
		out.close();
	}

	static int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	static String nextToken() throws IOException {
		while (st == null || !st.hasMoreTokens()) {
			String line = br.readLine();
			if (line == null) {
				return null;
			}
			st = new StringTokenizer(line);
		}
		return st.nextToken();
	}
}

Anagram Solution in Python

t=input()
for _ in range(t):
    s=raw_input()
    l=len(s)
    if(len(s) %2 != 0):print -1
    else:
        s1=s[:l/2]
        s2=s[l/2:]
        cnt1=[0 for _ in xrange(26)]
        cnt2=[0 for _ in xrange(26)]
        for c in s1:
            cnt1[ord(c)-ord('a')]+=1
        for c in s2:
            cnt2[ord(c)-ord('a')]+=1
        ans=0
        for i in xrange(26):
            ans+=abs(cnt1[i]-cnt2[i])
        print ans/2

Anagram Solution using JavaScript

var dup_fun = function (dup) {
    return function (c) {
        if (dup[c] === undefined) { dup[c] = 0; }
        dup[c]++;
    };
};

function processData(input) {
    var lines = input.split('\n');
    var T = parseInt(lines.shift(), 10);
    
    var data = lines.splice(0, T);

    var res = [];
    data.forEach(function (s) {
        if (s.length % 2 != 0) {
            res.push(-1);
            return;
        }
        var len = Math.floor(s.length / 2);
        var s1 = s.substr(0, len).split('');
        var s2 = s.substr(len).split('');
        var dup1 = {}; var dup_fun1 = dup_fun(dup1);
        var dup2 = {}; var dup_fun2 = dup_fun(dup2);
        s1.forEach(dup_fun1);
        s2.forEach(dup_fun2);

        var dist = 0;
        for (var i in dup1) {
            var d1 = dup1[i];
            var d2 = (dup2[i] === undefined) ? 0 : dup2[i];
            dist += Math.max(0, d1 - d2);
        }
        res.push(dist);
    });

    res.forEach(function (n) {
        process.stdout.write(n + '\n');
    });
}

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

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

Anagram Solution in Scala

var dup_fun = function (dup) {
    return function (c) {
        if (dup[c] === undefined) { dup[c] = 0; }
        dup[c]++;
    };
};

function processData(input) {
    var lines = input.split('\n');
    var T = parseInt(lines.shift(), 10);
    
    var data = lines.splice(0, T);

    var res = [];
    data.forEach(function (s) {
        if (s.length % 2 != 0) {
            res.push(-1);
            return;
        }
        var len = Math.floor(s.length / 2);
        var s1 = s.substr(0, len).split('');
        var s2 = s.substr(len).split('');
        var dup1 = {}; var dup_fun1 = dup_fun(dup1);
        var dup2 = {}; var dup_fun2 = dup_fun(dup2);
        s1.forEach(dup_fun1);
        s2.forEach(dup_fun2);

        var dist = 0;
        for (var i in dup1) {
            var d1 = dup1[i];
            var d2 = (dup2[i] === undefined) ? 0 : dup2[i];
            dist += Math.max(0, d1 - d2);
        }
        res.push(dist);
    });

    res.forEach(function (n) {
        process.stdout.write(n + '\n');
    });
}

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

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

Anagram Solution in Pascal

type 
  arr=array[0..26]of longint;
  procedure count(var ch:char;var A:arr);
  begin
  inc(A[ord(ch)-ord('a')+1]);
  end;
var
  i,ans,t,id:longint;
  Sa:ansistring;
  A,B:arr;
begin
  readln(t);
  for id:=1 to t do begin
    ans:=0;
    fillchar(A,sizeof(A),0);
    fillchar(B,sizeof(B),0);
    readln(Sa);
    if length(Sa) mod 2 =1 then begin
      writeln(-1);
      continue;
    end;
    for i:=1 to length(Sa) div 2 do count(Sa[i],A);
    for i:=(length(Sa) div 2 +1) to (length(Sa)) do count(Sa[i],B);
    for i:=1 to 26 do inc(ans,abs(A[i]-B[i]) );
    writeln(ans div 2);
  
  end;
end.

Disclaimer: This problem (Anagram) 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