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 :
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
The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →