Anagram


Problem Statement :


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 |  <=   10^4
s  consists only of characters in the range ascii[a-z].



Solution :



title-img


                            Solution in C :

In  C++  :






#include <string> 
#include <cmath>  
#include <cstdlib>  
#include <algorithm>  
#include <vector>  
#include <string.h>  
#include <utility>  
#include <queue>
#include <stack>
#include <iostream>  
#include <iomanip>  
#include <ctype.h>  
#include <sstream>  
#include <map> 
#include <set> 
#include <stdio.h>
#include <ctype.h>

using namespace std;

#define INF = 2000000000
#define FOR(i,n) for(int i = 0;i < n;i++)
#define CLEAR(x) memset((x),0,sizeof(x))
#define REP(i,a,b) for(int i = (a);i<(b);++i)
#define MP make_pair
#define ALL(a) (a).begin(),(a).end()
#define PB push_back
#define PII pair<int,int>
#define sz(a) (int)(a).size()

typedef long long LL;

int main(){
    ios_base::sync_with_stdio(0);
    int n;
    cin >> n;
    string s;
    int a[30];
    FOR(i,n){
        cin >> s;
        if (s.length()%2 == 1){
            cout << -1 << endl;
            continue;
        }
        
        CLEAR(a);
        FOR(j,s.length()/2){
            a[s[j]-'a']++;
        }
        int cnt = 0;
        FOR(j,s.length()/2){
            if (a[s[s.length()-j-1]-'a'] > 0 ){
                a[s[s.length()-j-1]-'a']--;
            }else
            cnt++;
        }
        cout << cnt << endl;
    }

    return 0;
}







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








In    C:







#include<string.h>
#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    
    while(t--)
    {
              char str[10005];
              int fre_a[27]={0},fre_b[27]={0},i,sum=0;
              scanf("%s",str);
              
              int len=strlen(str);
              
              if(len%2)
              printf("-1\n");
              
              else{
                   for(i=0;i<len/2;i++)
                   fre_a[str[i]-'a']++;
                   
                   for(i=len/2;i<len;i++)
                   fre_b[str[i]-'a']++;
                   
                   for(i=0;i<27;i++)
                   if(fre_b[i] && fre_b[i]>fre_a[i])
                   sum+=(fre_b[i]-fre_a[i]);
                   printf("%d\n",sum);
                   }
    }
    
    return 0;
}








In  Python3  :







T = int(input())
for i in range(0,T):
	al= (input())
	l = len(al)
	if (l%2==0):
		half = int(l/2)
		a = al[:half]
		b = al[half:]
		count = 0
		for c in a:
			if c in b:
				pos = b.find(c)
				b=b[:pos]+b[pos+1:]
			else:
			 count += 1
		print (count)
	else:
		print (-1)
                        








View More Similar Problems

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →