#K5246. Balanced String Checker
Balanced String Checker
Balanced String Checker
You are given a string S and your task is to check whether it is balanced. A string S is said to be balanced if and only if every distinct character in S appears the same number of times. In other words, for any two distinct characters (c_1) and (c_2) in S, the frequencies must satisfy (\text{freq}(c_1) = \text{freq}(c_2)). If S is balanced, output the number of distinct characters present in S; otherwise, output -1.
For example:
- For S = "aabb", each character appears 2 times, so the answer is 2.
- For S = "xyzxyz", each character appears 2 times, so the answer is 3.
- For S = "aabbb", the frequencies of 'a' and 'b' are different (2 and 3 respectively), so the answer is -1.
inputFormat
The input is given via standard input (stdin). The first line contains an integer T, representing the number of test cases. The following T lines each contain a non-empty string S consisting of lowercase letters.
outputFormat
For each test case, output a single integer in a new line: the number of distinct characters if the string is balanced, or -1 otherwise. The output should be written to standard output (stdout).## sample
5
aabb
xyzxyz
aabbb
apple
aabbccdd
2
3
-1
-1
4
</p>