Equal Frequencies (Codeforces 1781C)
Tags: Greedy, strings

Let's call a string balanced if all characters that are present in it appear the same number of times. For example, "coder", "appall", and "ttttttt" are balanced, while "wowwow" and "codeforces" are not.You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters. Find a balanced string $$$t$$$ of the same length $$$n$$$ consisting of lowercase English letters that is different from the string $$$s$$$ in as few positions as possible. In other words, the number of indices $$$i$$$ such that $$$s_i \ne t_i$$$ should be as small as possible.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$.The second line contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output: For each test case, print the smallest number of positions where string $$$s$$$ and a balanced string $$$t$$$ can differ, followed by such a string $$$t$$$.If there are multiple solutions, print any. It can be shown that at least one balanced string always exists.

Note: In the first test case, the given string "hello" is not balanced: letters 'h', 'e', and 'o' appear in it once, while letter 'l' appears twice. On the other hand, string "helno" is balanced: five distinct letters are present in it, and each of them appears exactly once. Strings "hello" and "helno" differ in just one position: the fourth character. Other solutions are possible too.In the second test case, string "codefofced" is balanced since only letters 'c', 'o', 'd', 'e', and 'f' are present in it, and each of them appears exactly twice.In the third test case, string "eeeee" is balanced since only letter 'e' is present in it.In the fourth test case, the given string "appall" is already balanced.

Sample Inputs:
4
5
hello
10
codeforces
5
eevee
6
appall

Sample Outputs:
1
helno
2
codefofced
1
eeeee
0
appall

Solution (Python):
import random

def convert_str(ns, best_k, c, csort):
    nsb = len(ns) / best_k
    numletters = len(c) - c.count(0)
    let_a = ord('a')
    usedletters = []
    for i in range(min(best_k, numletters)):
        if i == 0 or csort[i] != csort[i - 1]:
            si = 0
        si = c.index(csort[i], si)
        usedletters.append(si)
        si = si + 1
    si = 0
    for i in range(max(0, best_k - numletters)):
        si = c.index(0, si)
        usedletters.append(si)
        si = si + 1
    ulc = [0] * len(usedletters)
    for i in range(len(ns)):
        ns[i] = ord(ns[i]) - let_a
        if ns[i] in usedletters:
            li = usedletters.index(ns[i])
            if ulc[li] < nsb:
                ulc[li] += 1
                continue
        ns[i] = -1
    for i in range(len(ns)):
        if ns[i] == -1:
            for k in range(len(usedletters)):
                if ulc[k] < nsb:
                    ulc[k] += 1
                    ns[i] = usedletters[k]
                    break
    for i in range(len(s)):
        ns[i] = chr(ns[i] + let_a)
    return ns

def solve(s, n):
    let_a = ord('a')
    c = [0] * 26
    for ch in s:
        c[ord(ch) - let_a] += 1
    numletters = len(c) - c.count(0)
    csort = sorted(c, reverse=True)
    min_ndiff = n + 1
    best_k = -1
    for k in range(1, 27):
        if len(s) % k == 0:
            nsb = len(s) / k
            ndiff = 0
            for z in range(min(numletters, k)):
                if csort[z] < nsb:
                    ndiff += nsb - csort[z]
            ndiff += (k - min(numletters, k)) * nsb
            if ndiff < min_ndiff:
                min_ndiff = int(ndiff)
                best_k = k
    ns = s.copy()
    if min_ndiff > 0:
        ns = convert_str(ns, best_k, c, csort)
    return (min_ndiff, ns)
t = int(input())
if t < 0:
    t = -t
    for ti in range(t):
        n = random.randrange(2, 20000)
        s = [0] * n
        for ni in range(n):
            s[ni] = chr(random.randrange(ord('a'), ord('z')))
        res = solve(list(s), n)
        ndiff = 0
        ncount = res[1].count(res[1][0])
        for ni in range(n):
            if s[ni] != res[1][ni]:
                ndiff += 1
        if ndiff != res[0]:
            print(s, res[0], res[1], ndiff)
else:
    ans = []
    for ti in range(t):
        n = int(input())
        s = input()
        ans.append(solve(list(s), n))
    for a in ans:
        print(a[0])
        print(''.join((c for c in a[1])))

Solution (Python):
import math
T = int(input())
while T > 0:
    T -= 1
    n = int(input())
    s = input()
    cnt = {}
    for i in range(n):
        if cnt.get(s[i]) != None:
            cnt[s[i]] += 1
        else:
            cnt[s[i]] = 1
    a = []
    for key in cnt.keys():
        a.append((cnt[key], key))
    a.sort(key=lambda x: -x[0])
    left_type = -1
    max_same_cnt = -1
    for type in range(1, 27, 1):
        if n % type != 0:
            continue
        same_cnt = n // type
        change = 0
        if type <= len(a):
            for i in range(type):
                if a[i][0] > same_cnt:
                    change += a[i][0] - same_cnt
            for i in range(type, len(a), 1):
                change += a[i][0]
        else:
            for i in range(len(a)):
                if a[i][0] > same_cnt:
                    change += a[i][0] - same_cnt
        if max_same_cnt < n - change:
            max_same_cnt = n - change
            left_type = type
    print(n - max_same_cnt)
    res = list(s)
    each_char_cnt = n // left_type
    final_charset = {}
    if left_type <= len(a):
        for i in range(left_type):
            final_charset[a[i][1]] = a[i][0]
    else:
        for i in range(len(a)):
            final_charset[a[i][1]] = a[i][0]
        other = left_type - len(a)
        for i in range(26):
            if final_charset.get(chr(ord('a') + i)) == None:
                final_charset[chr(ord('a') + i)] = 0
                other -= 1
                if other == 0:
                    break
    for i in range(n):
        if final_charset.get(res[i]) == None:
            for key in final_charset.keys():
                if final_charset[key] < each_char_cnt:
                    final_charset[key] += 1
                    res[i] = key
                    break
        else:
            if final_charset[res[i]] <= each_char_cnt:
                continue
            for key in final_charset.keys():
                if final_charset[key] < each_char_cnt:
                    final_charset[key] += 1
                    final_charset[res[i]] -= 1
                    res[i] = key
                    break
    for i in range(n):
        print(res[i], end='')
    print()

Solution (Python):
import sys
import math
input = sys.stdin.readline
for _ in range(int(input())):
    n = int(input())
    s = list(input())
    a = [[0, i] for i in range(26)]
    b = []
    for i in range(1, n + 1):
        if n % i == 0 and n // i <= 26:
            b.append(i)
    for i in range(n):
        a[ord(s[i]) - 97][0] += 1
    a.sort(reverse=True)
    res = float('inf')
    idx = float('inf')
    for i in b:
        (x, y) = (0, 0)
        for j in range(n // i):
            if a[j][0] > i:
                x += a[j][0] - i
                y += a[j][0] - i
                continue
            x += max(i - y - a[j][0], 0)
            y -= min(i - a[j][0], y)
        (res, idx) = min([res, idx], [x, i])
    print(res)
    d = {}
    for i in range(n // idx):
        d[chr(a[i][1] + 97)] = idx
    s1 = [None] * n
    for i in d.keys():
        for j in range(n):
            if s[j] == i and d[i] > 0:
                s1[j] = i
                d[i] -= 1
    b = []
    for i in range(n):
        if s1[i] == None:
            b.append(i)
    c = []
    for i in d.keys():
        c += [i] * d[i]
    for i in range(len(c)):
        s1[b[i]] = c[i]
    print(''.join(s1))