Equal Frequencies (Codeforces 1782C)
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 sys
input = sys.stdin.readline

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    (n, s) = (readInt(), list(readStr()))
    cnt = [0] * 26
    for i in range(n):
        cnt[ord(s[i]) - ord('a')] += 1
    cnt = sorted([(v, chr(i + ord('a'))) for (i, v) in enumerate(cnt)], reverse=True)
    (res, save) = (n, 0)
    for i in range(26):
        if n % (i + 1):
            continue
        v = n - sum([min(n // (i + 1), cnt[j][0]) for j in range(i + 1)])
        if v < res:
            res = v
            save = i + 1
    print(res)
    curr = [0] * 26
    (ext, bag) = (list(''.join([c[1] * max(n // save - c[0], 0) for c in cnt[:save]])), [c[1] for c in cnt[:save]])
    for i in range(n):
        if s[i] in bag:
            if curr[ord(s[i]) - ord('a')] < n // save:
                curr[ord(s[i]) - ord('a')] += 1
            else:
                s[i] = ext.pop()
        else:
            s[i] = ext.pop()
    print(''.join(s))
    return
for _ in range(readInt()):
    solve()

Solution (Python):
alphabet = set('abcdefghijklmnopqrstuvwxyz')
t = int(input())
for _ in range(t):
    n = int(input())
    s = input()
    dic = {}
    for let in s:
        if let not in dic:
            dic[let] = 1
        else:
            dic[let] += 1
    A = list(dic.values())
    A.sort(reverse=True)
    max_sum = -1
    k_max = -1
    for k in range(1, n + 1):
        if n % k == 0:
            d = n // k
            if d <= 26:
                sum = 0
                for j in range(min(d, len(A))):
                    sum += min(k, A[j])
                if sum > max_sum:
                    max_sum = sum
                    k_max = k
    ans = n - max_sum
    print(ans)
    k = k_max
    d = n // k
    add_letts = set()
    kolvo = 0
    if d >= len(dic):
        for elem in alphabet:
            if kolvo == d - len(dic):
                break
            if elem not in dic:
                add_letts.add(elem)
                kolvo += 1
        need = {}
        for let in add_letts:
            need[let] = k
        for let in dic:
            if dic[let] < k:
                need[let] = k - dic[let]
        met = {}
        for el in dic:
            met[el] = 0
        S = ''
        for let in s:
            met[let] += 1
            if met[let] > k:
                val = list(need.keys())[0]
                S += val
                need[val] -= 1
                if need[val] == 0:
                    need.pop(val)
            else:
                S += let
        print(S)
    else:
        take = set()
        added = 0
        for qq in range(d):
            for elem in dic:
                if added == d:
                    break
                if dic[elem] == A[qq] and elem not in take:
                    take.add(elem)
                    added += 1
        need = {}
        for let in dic:
            if dic[let] < k and let in take:
                need[let] = k - dic[let]
        met = {}
        for el in take:
            met[el] = 0
        S = ''
        for let in s:
            if let in take:
                met[let] += 1
            if len(need) != 0:
                val = list(need.keys())[0]
            if let not in take:
                S += val
                need[val] -= 1
                if need[val] == 0:
                    need.pop(val)
            elif met[let] > k:
                S += val
                need[val] -= 1
                if need[val] == 0:
                    need.pop(val)
            else:
                S += let
        print(S)

Solution (Python):
from sys import stdin, stdout

def I():
    return stdin.readline().strip(' \r\n')

def II():
    return int(I())

def IL():
    return I().split()

def ICL():
    return list(I())

def IIL():
    return list(map(int, IL()))

def IM():
    return map(str, IL())

def IIM():
    return map(int, IL())

def ICIM():
    return map(int, ICL())

def P(*args, sep=' ', end=''):
    stdout.write(sep.join([str(s) for s in args]) + end)

def PL(*args, sep=' '):
    P(*args, sep=sep, end='\n')

def F():
    stdout.flush()

def main():
    for _ in range(II()):
        solve()

def solve():
    n = II()
    s = I()
    ltct = {}
    for c in s:
        if c not in ltct:
            ltct[c] = 0
        ltct[c] += 1
    grp = sorted(list(([v, k] for (k, v) in ltct.items())), reverse=True)
    unused = [c for c in 'abcdefghijklmnopqrstuvwxyz' if c not in ltct]
    for _ in range(len(unused)):
        grp.append([0, unused.pop()])
    fpair = []
    for k in range(1, 27):
        if not n % k:
            fpair.append((k, n // k))
    mindiff = (float('inf'),)
    for (nl, no) in fpair:
        sm = 0
        for (idx, v) in enumerate(grp):
            if idx >= nl:
                sm += v[0]
            else:
                sm += max(v[0] - no, 0)
        mindiff = min(mindiff, (sm, nl, no))
    should = [mindiff[2]] * mindiff[1] + [0] * 26
    gain = []
    lose = {}
    grp = grp[:max(mindiff[1], len(ltct))]
    for (idx, vk) in enumerate(grp):
        if vk[0] > should[idx]:
            lose[vk[1]] = vk[0] - should[idx]
        elif vk[0] < should[idx]:
            gain.append([vk[1], should[idx] - vk[0]])
    out = ''
    for c in s:
        if c in lose:
            lose[c] -= 1
            if not lose[c]:
                lose.pop(c)
            out += gain[-1][0]
            gain[-1][1] -= 1
            if not gain[-1][1]:
                gain.pop()
        else:
            out += c
    PL(mindiff[0])
    PL(out)
if __name__ == '__main__':
    main()