Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerRank Anagram problem solution

YASH PAL, 31 July 202423 January 2026

HackerRank Anagram problem solution – In this HackerRank Anagram problem, 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.

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

HackerRank Anagram 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))

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

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("-1n");

    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("%dn", total);
    }
  }

  return 0;
}

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("%[^tn]s",arr);
        len = strlen(arr);
        if(len % 2 != 0){
            printf("-1n");
        }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("%dn",totalchange);
        }
        --tests;
        for(i = 0;i<26;++i){
			count[i] = 0;
        }
        totalchange = 0;
    }
    return 0;
}

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

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

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes