# 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.

## HackerRank Anagram Solution

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

### HackerRank 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;
}```

### HackerRank 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;
}```

### HackerRank 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();
}
}

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 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");
input = new FileInputStream(file);
}
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()) {
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}```

### HackerRank 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```

### HackerRank 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);
});```

### HackerRank 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);
});```

### HackerRank 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
for id:=1 to t do begin
ans:=0;
fillchar(A,sizeof(A),0);
fillchar(B,sizeof(B),0);
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.

Sharing Is Caring