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

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →