In this HackerRank Anagram problem we have 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.

HackerRank Anagram problem solution


Problem solution in Python.

import sys

def score(word):
        if len(word) & 1:
                return -1
        mid = int(len(word)/2)
        a = word[0:mid]
        b = list(word[mid:])
        num = 0
        for i in range(len(a)):
                try:   
                        b.remove(a[i])
                except ValueError:
                        num += 1
        return num

num = int(sys.stdin.readline())

for i in range(num):
        s = sys.stdin.readline().strip()
        print(score(s))

{"mode":"full","isActive":false}


Problem solution in Java.

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

class Solution {

    public static void main(String[] args) throws IOException{
    	BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
    	int test = Integer.parseInt(bis.readLine());
    	for(int t=0;t<test;t++){
    		String s = bis.readLine();
    		char temp[]=s.toCharArray();
    	int length = s.length();
    	int fre[][]=new int[26][2];
    	if(length%2!=0){
    		System.out.println("-1");
    		continue;
    	}
    	
    	int mid = length/2;
    	int inc=0;
    	for(int i=0;i<length;i++){
    		if(i==mid)
             	inc++;
    		
                fre[temp[i]-'a'][inc]++;
             }
             int ans=0;
             for(int i=0;i<26;i++){
    		ans=ans+Math.abs(fre[i][0]-fre[i][1]);
    	}
         System.out.println(ans/2);    
             
    		
    	}
    	
        
    }
}

{"mode":"full","isActive":false}


Problem solution in C++.

#include <stdio.h>
#include <string.h>
#include <map>

int main(int argc, char *argv[]) {
  std::map<char,int> a, b;
  static char str[10000+1];
  int n, total;
  size_t len;

  scanf("%d", &n);

  for(int i = 0; i < n; ++i) {
    a.clear();
    b.clear();
    total = 0;

    scanf("%s", str);
    if((len = strlen(str)) % 2 != 0)
      printf("-1\n");

    else {
      for(size_t j = 0; j < len/2; ++j)
        a[str[j]] += 1;
      for(size_t j = len/2; j < len; ++j)
        b[str[j]] += 1;

      for(auto it = a.begin(); it != a.end(); ++it) {
        if(b.count(it->first) > 0) {
          if(b[it->first] < it->second) {
            it->second -= b[it->first];
            b[it->first] = 0;
          }
          else {
            b[it->first] -= it->second;
            it->second = 0;
          }
        }
      }

      for(auto it = a.begin(); it != a.end(); ++it)
        total += it->second;

      printf("%d\n", total);
    }
  }

  return 0;
}

{"mode":"full","isActive":false}


Problem solution in C.

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

int main() {
    int tests,i,temp,len = 0,totalchange = 0;
    char arr[10000];
    int count[26] = {0};
    scanf("%d",&tests);
    while(tests>0){
		getchar();
        scanf("%[^\t\n]s",arr);
        len = strlen(arr);
        if(len % 2 != 0){
            printf("-1\n");
        }else{
            for(i = len/2;i<len;++i){
				temp = (int)arr[i]-97;
                count[temp]++;
            }
            for(i = 0;i<len/2;++i){
				temp = (int)arr[i] - 97;
				if(count[temp] == 0)continue;
                	count[temp]--;
            }
            for(i = 0;i<26;++i){
                totalchange = totalchange + count[i];
            }
            printf("%d\n",totalchange);
        }
        --tests;
        for(i = 0;i<26;++i){
			count[i] = 0;
        }
        totalchange = 0;
    }
    return 0;
}