Anagram – HackerRank Solution

In this post, we will solve Anagram HackerRank Solution. This problem (Anagram) is a part of HackerRank Problem Solving Series.

Contents

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 ‘a’ and ‘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 =’aaa’ and 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”.

Solution – Anagrams – HackerRank Solution

C++

#include <iostream>
#include <string>
#include <map>

using namespace std;

int getChangesToAnagram(string s1, string s2) {
    int total, N1;
    int N2 = s2.size();
    map<char, int> charCount;

    total = N1 = s1.size();

    if (N1 != N2) return -1;

    for (int i = 0; i < N2; i++)
        charCount[s2[i]]++;

    for (int i = 0; i < N1; i++) {
        if (charCount[s1[i]] > 0) {
            total--;
            charCount[s1[i]]--;
        }
    }

    return total;
}

int main() {
    int N;
    cin >> N;

    for (int i = 0; i < N; i++) {
        string s;
        cin >> s;
        cout << getChangesToAnagram(s.substr(0, s.size() / 2), s.substr(s.size() / 2)) << endl;
    }
}

Python

#!/bin/python3

import sys
from collections import Counter

def anagram(s):
    if len(s)%2 == 1:
        return -1
    
    res = 0
    
    cnt1 = Counter(s[:len(s)//2])
    cnt2 = Counter(s[len(s)//2:])
    cnt3 = {}
    
    for let, val in cnt1.items():
        cnt3[let] = abs(val - cnt2[let])
    for let, val in cnt2.items():
        cnt3[let] = abs(val - cnt1[let])
        
    for el in cnt3.values():
        res += el
    
    return res//2

q = int(input().strip())
for a0 in range(q):
    s = input().strip()
    result = anagram(s)
    print(result)

Java

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

public class Solution {

    static int anagram(String s){
        if (s.length() % 2 != 0) { return -1; }
        int[] cache = new int[70];

        for (int i = 0; i < s.length() / 2; i++) {
            cache[Character.getNumericValue(s.charAt(i))]++;
        }

        for (int i = s.length() / 2; i < s.length(); i++) {
            if (cache[Character.getNumericValue(s.charAt(i))] > 0) {
                cache[Character.getNumericValue(s.charAt(i))]--;
            }
        }

        int counter = 0;
        for (int i = 0; i < 70; i++) {
            counter += cache[i];
        }

        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String s = in.next();
            int result = anagram(s);
            System.out.println(result);
        }
    }
}

Note: This problem (Anagrams) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

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