Polycarp was gifted an array $a$ of length $n$. Polycarp considers an array beautiful if there exists a number $C$, such that each number in the array occurs either zero or $C$ times. Polycarp wants to remove some elements from the array $a$ to make it beautiful.

For example, if $n=6$ and $a = [1, 3, 2, 1, 4, 2]$, then the following options are possible to make the array $a$ array beautiful:

Polycarp removes elements at positions $2$ and $5$, array $a$ becomes equal to $[1, 2, 1, 2]$;

Polycarp removes elements at positions $1$ and $6$, array $a$ becomes equal to $[3, 2, 1, 4]$;

Polycarp removes elements at positions $1, 2$ and $6$, array $a$ becomes equal to $[2, 1, 4]$;

Help Polycarp determine the minimum number of elements to remove from the array $a$ to make it beautiful.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of each test case consists of one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — array $a$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, output one integer — the minimum number of elements that Polycarp has to remove from the array $a$ to make it beautiful.


-----Examples-----

Input
3
6
1 3 2 1 4 2
4
100 100 4 100
8
1 2 3 3 3 2 6 6
Output
2
1
2


-----Note-----

None

Difficulty: MEDIUM

Solutions:
import math
import collections

def read_list() -> list:
	return [int(i) for i in input().strip().split()]

def read_num() -> int:
	return int(input().strip())
t = read_num()
while t > 0:
	t -= 1
	n = read_num()
	arr = read_list()
	cnt = collections.Counter(arr)
	appear_times_cnt = collections.Counter(cnt.values())
	remove_needs = [(k, v) for (k, v) in appear_times_cnt.items()]
	l = len(remove_needs)
	ans = float('inf')
	for i in range(l):
		tmp = 0
		for j in range(l):
			if remove_needs[j][0] - remove_needs[i][0] < 0:
				tmp += remove_needs[j][0] * remove_needs[j][1]
			else:
				tmp += min(remove_needs[j][0] - remove_needs[i][0], remove_needs[j][0]) * remove_needs[j][1]
		ans = min(tmp, ans)
	print(ans)


get_line = lambda type_: list(map(type_, input().strip().split()))
from collections import Counter

def solve():
	n = int(input())
	a = get_line(int)
	c = Counter(a)
	his = [i[1] for i in c.items()]
	his.sort()
	max_rect_area = 0
	last_h = 0
	for (i, h) in enumerate(his):
		if h != last_h:
			if h * (len(his) - i) > max_rect_area:
				max_rect_area = h * (len(his) - i)
			last_h = h
	print(sum(his) - max_rect_area)
t = int(input())
for _ in range(t):
	solve()


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	C = Counter(A)
	l = [0] * (n + 1)
	for c in C.values():
		l[c] += 1
	ans = n
	cuml = [0] * (n + 1)
	for i in range(1, n + 1):
		cuml[i] = cuml[i - 1] + l[i] * i
	count = 0
	now = 0
	for i in range(n + 1)[::-1]:
		if l[i] == 0 and count == 0:
			continue
		calc = cuml[i - 1] + now
		ans = min(ans, calc)
		count += l[i]
		now += count
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	b = []
	cr = a[0]
	cnt = 1
	for i in range(1, n):
		if a[i] == cr:
			cnt += 1
		else:
			b.append(cnt)
			cnt = 1
			cr = a[i]
	b.append(cnt)
	b.sort()
	c = [b[0]]
	d = []
	cr = b[0]
	cnt = 1
	for i in range(1, len(b)):
		if b[i] == cr:
			cnt += 1
		else:
			d.append(cnt)
			cnt = 1
			cr = b[i]
			c.append(cr)
	d.append(cnt)
	ans = []
	for i in range(len(c)):
		sm = 0
		for j in range(i):
			sm += c[j] * d[j]
		for j in range(i + 1, len(c)):
			sm += (c[j] - c[i]) * d[j]
		ans.append(sm)
	print(min(ans))


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	(c, d) = ({}, {})
	for i in a:
		if i not in d:
			d[i] = 0
		d[i] += 1
		if d[i] not in c:
			c[d[i]] = 0
		c[d[i]] += 1
	arr = [i * c[i] for i in c]
	print(n - max(arr))
for _ in range(int(input())):
	solve()


def solve():
	n = int(input())
	arr = [int(i) for i in input().split()]
	dic = {}
	for i in range(n):
		if arr[i] in dic:
			dic[arr[i]] += 1
		else:
			dic[arr[i]] = 1
	values = list(dic.values())
	deleted = []
	for s in set(values):
		result = sum([a - s for a in values if a > s])
		result += sum([a for a in values if a < s])
		deleted.append(result)
	print(min(deleted))
for _ in range(int(input())):
	solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	l = [*map(int, input().split())]
	d = {}
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	c = sorted(d.values())
	dd = {}
	for i in c:
		if i in dd:
			dd[i] += 1
		else:
			dd[i] = 1
	cs = list(dd.keys())
	cc = list(dd.values())
	ll = len(cs)
	a = sum(((cs[i] - cs[0]) * cc[i] for i in range(1, ll)))
	m = a
	scc = []
	sm = 0
	for i in range(ll - 1, -1, -1):
		sm += cc[i]
		scc = [sm] + scc
	for i in range(1, ll):
		a += cs[i - 1] * cc[i - 1]
		a -= (cs[i] - cs[i - 1]) * scc[i]
		m = min(m, a)
	print(m)


t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	tmp = {}
	for x in arr:
		tmp[x] = tmp.get(x, 0) + 1
	arr0 = list(tmp.values())
	n = len(arr0)
	arr1 = sorted(arr0)
	s = sum(arr0)
	arr2 = [s - (n - i) * arr1[i] for i in range(n)]
	print(min(arr2))


import sys, os, io
from collections import defaultdict
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	dic = defaultdict(lambda : 0)
	for i in a:
		dic[i] += 1
	b = []
	for i in dic:
		b.append([dic[i], i])
	b.sort()
	ans = n - b[0][0] * len(b)
	curr = 0
	for i in range(len(b) - 1):
		curr += b[i][0]
		ans = min(ans, n - b[i + 1][0] * (len(b) - i - 1))
	print(ans)


from collections import Counter

def get_cost(freq, k):
	cost = 0
	for (x, f) in freq.items():
		if x < k:
			cost += f * x
		else:
			cost += (x - k) * f
	return cost

def solve():
	input()
	freq = Counter(input().split()).values()
	freq_freq = Counter(freq)
	mn = min((get_cost(freq_freq, x) for x in freq_freq))
	print(mn)
t = int(input())
for _ in range(t):
	solve()


for _ in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	d = {}
	for word in ls:
		d[word] = d.get(word, 0) + 1
	ls = sorted(d.values())
	(cost, ans) = (0, 0)
	for j in range(len(ls)):
		cost = (len(ls) - j) * ls[j]
		if cost > ans:
			ans = cost
	print(n - ans)


import sys
input = sys.stdin.readline
from collections import Counter

def read():
	N = int(input().strip())
	A = list(map(int, input().strip().split()))
	return (N, A)

def solve(N, A):
	C = list(Counter(A).values())
	C.sort()
	S = sum(C)
	ans = S
	R = len(C)
	for i in range(R):
		rect = C[i] * (R - i)
		ans = min(ans, S - rect)
	print(ans)
T = int(input().strip())
for t in range(T):
	inputs = read()
	solve(*inputs)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	dic = dict()
	for i in range(n):
		if a[i] in dic.keys():
			dic[a[i]] += 1
		else:
			dic[a[i]] = 1
	nums = []
	for i in dic.values():
		nums.append(i)
	nums.sort()
	SUM = sum(nums)
	ans = SUM
	left = 0
	for i in range(len(nums)):
		temp = SUM - nums[i] * (len(nums) - i)
		ans = min(temp, ans)
	print(ans)


from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))

def fast():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (fast, lambda : list(map(int, z().split())))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer, end='\n'):
	stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
num = int(z())
for _ in range(num):
	n = int(z())
	arr = szzz()
	cnt = [0] * (n + 1)
	(i, j) = (0, 0)
	while i < n:
		while j < n and arr[i] == arr[j]:
			j += 1
			cnt[j - i] += j - i
		i = j
	ans = 0
	for i in range(n + 1):
		ans = max(ans, cnt[i])
	print(n - ans)


def codeforces(arr):
	dist = {}
	for i in arr:
		try:
			dist[i] += 1
		except:
			dist[i] = 1
	dst = {}
	for i in dist:
		try:
			dst[dist[i]] += 1
		except:
			dst[dist[i]] = 1
	res = 0
	for i in dst:
		store = i
		break
	for i in dst:
		if i >= store:
			res += dst[i] * min(i, abs(i - store))
		else:
			res += dst[i] * i
	for i in dst:
		store = i
		ans = 0
		for ind in dst:
			if ind >= store:
				ans += dst[ind] * min(ind, abs(ind - store))
			else:
				ans += dst[ind] * ind
		res = min(ans, res)
	return res
t = int(input())
for test in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	print(codeforces(arr))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	mp = {}
	reps = []
	for i in arr:
		if i in mp:
			mp[i] += 1
		else:
			mp[i] = 1
	for i in mp:
		reps.append(mp[i])
	reps.sort()
	diff = list(set(reps))
	ans = 10 ** 9
	for x in diff:
		curr = 0
		for i in reps:
			if x == i:
				pass
			elif i < x:
				curr += i
			else:
				curr += i - x
		ans = min(ans, curr)
	print(ans)


import math
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	d = {}
	ans = []
	for num in arr:
		if num in d:
			d[num] += 1
		else:
			d[num] = 1
	mx = max(d.values())
	l = len(d.values())
	counter = [0] * (mx + 1)
	for num in d.values():
		counter[num] += 1
	count = counter[0]
	for i in range(1, mx + 1):
		old = counter[i]
		counter[i] = (l - count) * i
		count = count + old
	print(n - max(counter[1:]))


from collections import Counter

def solve(n, a):
	cnt = Counter(a)
	b = list(sorted(cnt.values()))
	total = sum(b)
	s = 0
	res = total
	for (i, e) in enumerate(b):
		r = total - s - e - e * (len(b) - i - 1)
		res = min(res, s + r)
		s += e
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(n, a))


def find():
	n = int(input())
	mas = tuple(map(int, input().split()))
	count_numbers = {}
	for j in mas:
		count_numbers[j] = count_numbers.get(j, 0) + 1
	count_set_numb = {}
	for j in count_numbers:
		count_set_numb[count_numbers[j]] = count_set_numb.get(count_numbers[j], 0) + 1
	res = n
	last = 0
	all_next = n
	uniq_next = len(count_numbers)
	for j in sorted(count_set_numb):
		res = min(res, last + all_next - uniq_next * j)
		last += j * count_set_numb[j]
		all_next -= j * count_set_numb[j]
		uniq_next -= count_set_numb[j]
	print(res)
for i in range(int(input())):
	find()


t = int(input())
for q in range(t):
	n = int(input())
	ch = input()
	L = [int(i) for i in ch.split()]
	d = dict()
	for i in L:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	L = list(d.values())
	n = len(L)
	L.sort()
	if n == 1:
		print(0)
		continue
	sm = [L[0]] * n
	dp = [0] * n
	for i in range(1, n):
		sm[i] = sm[i - 1] + L[i]
	dp[0] = sm[-1] - sm[0] - L[0] * (n - 1)
	dp[n - 1] = sm[-2]
	for i in range(1, n - 1):
		dp[i] = sm[i - 1] + (sm[-1] - sm[i]) - L[i] * (n - 1 - i)
	print(min(dp))


from collections import Counter
from math import inf

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		ocurrencias = list(Counter(a).values())
		search = Counter(ocurrencias)
		ans = inf
		for (i, k) in search.items():
			temp = 0
			for (j, l) in search.items():
				if i != j:
					if i < j:
						temp += (j - i) * l
					else:
						temp += j * l
			ans = min(ans, temp)
		print(ans)
main()


from collections import *
I = input
for _ in ' ' * int(I()):
	s = n = int(I())
	c = 0
	for (x, y) in sorted(Counter(Counter(map(int, I().split())).values()).items())[::-1]:
		c += y
		s = min(s, n - c * x)
	print(s)
num_inp = lambda : int(input())
arr_inp = lambda : list(map(int, input().split()))
sp_inp = lambda : map(int, input().split())
str_inp = lambda : input()


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	d = {}
	k = 0
	A = []
	for j in arr:
		if j in d.keys():
			d[j] += 1
		else:
			k += 1
			d.update({j: 1})
	for j in d:
		A.append(d[j])
	A.sort()
	A.reverse()
	q = 0
	for j in range(1, k + 1):
		q = max(q, j * A[j - 1])
	print(n - q)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	d = Counter(a)
	dict = {}
	for i in d:
		if d[i] in dict:
			dict[d[i]] += 1
		else:
			dict[d[i]] = 1
	c = [d[i] for i in d]
	c = list(set(c))
	c.sort()
	ans = n
	s = len(set(a))
	for ele in range(len(c)):
		i = c[ele]
		tmp = dict[i] * i + (s - dict[i]) * i
		s -= dict[i]
		ans = min(ans, n - tmp)
	print(ans)


from collections import defaultdict as dict

def solve():
	n = int(input())
	c = dict(int)
	for x in input().split():
		c[int(x)] += 1
	a = sorted(c.values())
	v = [0]
	prev = a[0]
	for i in range(1, len(a)):
		if a[i] != prev:
			v.append(i)
			prev = a[i]
	s = a.copy()
	for i in range(1, len(a)):
		s[i] += s[i - 1]
	ans = 10 ** 18
	n = len(a)
	for i in v:
		ans = min(ans, s[i] - a[i] + (s[-1] - s[i]) - a[i] * (n - i - 1))
	print(ans)
for _ in ' ' * int(input()):
	solve()


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return tmp[:x]

def err(x):
	print(x)
	exit()
for _ in range(inp()):
	n = inp()
	a = inpl()
	c = Counter(a)
	vas = sorted(list(c.values()))
	acc = [0]
	for x in vas:
		acc.append(acc[-1] + x)
	res = INF
	ln = len(vas)
	for now in list(set(vas)):
		cnt = 0
		l = bisect_left(vas, now)
		r = bisect_right(vas, now)
		cnt = acc[l] + acc[-1] - acc[r] - now * (ln - r)
		res = min(res, cnt)
	print(res)


import sys
input = iter(sys.stdin.read().splitlines()).__next__

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	freq = {a_i: 0 for a_i in a}
	for a_i in a:
		freq[a_i] += 1
	counts = sorted(freq.values())
	removed = sum(counts) - len(counts) * counts[0]
	best = removed
	for i in range(1, len(counts)):
		C = counts[i]
		removed += counts[i - 1]
		removed -= (len(counts) - i) * (C - counts[i - 1])
		best = min(best, removed)
	return best
t = int(input())
output = []
for _ in range(t):
	output.append(solve())
print(*output, sep='\n')


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	numbers = list(map(int, input().split()))
	d = Counter(numbers)
	d1 = Counter(d.values())
	d2_s = sorted(d1.items())
	summ_right = 0
	for i in range(len(d2_s)):
		summ_right += d2_s[i][1]
	minn = n
	current_sum = n
	t = 0
	for i in range(len(d2_s)):
		if i != 0:
			current_sum += d2_s[i - 1][1] * d2_s[i - 1][0]
		summ_right -= d2_s[i][1]
		current_sum += n - current_sum - d2_s[i][0] * d2_s[i][1] - summ_right * d2_s[i][0]
		t = d2_s[i][0]
		if current_sum < minn:
			minn = current_sum
	print(minn)


t = int(input())
for _ in range(t):
	n = int(input())
	ls = list(map(int, input().split()))
	d = {}
	d2 = {}
	for i in ls:
		d[i] = d.setdefault(i, 0) + 1
	for i in d.values():
		d2[i] = d2.setdefault(i, 0) + 1
	ans = n
	temp = len(d)
	temp2 = sorted(d2.keys())
	for x in temp2:
		ans = min(ans, n - temp * x)
		temp -= d2[x]
	print(ans)


def solve(a):
	li = get_counts(a)
	solution = 0
	for i in range(len(li)):
		temp_solution = li[i] * (len(li) - i)
		if temp_solution > solution:
			solution = temp_solution
	print(len(a) - solution)

def get_counts(li):
	count_dict = {}
	for a in li:
		if a in count_dict:
			count_dict[a] += 1
		else:
			count_dict[a] = 1
	return sorted(count_dict.values())

def main():
	x = input()
	for _ in range(int(x)):
		input()
		a = input()
		solve(list(map(int, a.split())))
main()


from collections import Counter, defaultdict
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	numbers_and_their_frequency = Counter(a)
	the_num_of_each = defaultdict(int)
	for num in numbers_and_their_frequency:
		the_num_of_each[numbers_and_their_frequency[num]] += 1
	the_num_of_each = {key: the_num_of_each[key] for key in sorted(the_num_of_each)}
	min_of_deletions = float('inf')
	m = len(the_num_of_each)
	for key in the_num_of_each:
		local_min_of_deletions = 0
		the_num_of_each_copy = the_num_of_each.copy()
		for local_key in the_num_of_each_copy:
			if local_key < key:
				local_min_of_deletions += local_key * the_num_of_each_copy[local_key]
			else:
				local_min_of_deletions += (local_key - key) * the_num_of_each_copy[local_key]
		min_of_deletions = min(min_of_deletions, local_min_of_deletions)
	print(min_of_deletions)


def main():
	t = int(input())
	result = []
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		cnt = {}
		for val in a:
			cnt[val] = cnt.get(val, 0) + 1
		cnt_ordered = sorted(cnt.values())
		cnt_ordered_n = len(cnt_ordered)
		s = 0
		same_val_cnt = 0
		last_val = -1
		ans = 10 ** 7
		for (i, val) in enumerate(cnt_ordered):
			s += val
			if last_val == val:
				same_val_cnt += 1
			else:
				same_val_cnt = 1
			last_val = val
			cnt_less = s - same_val_cnt * val
			cnt_more = n - s
			ans = min(ans, cnt_less + cnt_more - val * (cnt_ordered_n - i - 1))
		result.append(str(ans))
	print('\n'.join(result))
main()


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	b = []
	c = 0
	for j in range(1, n):
		if a[j] != a[j - 1]:
			b.append(j - c)
			c = j
	b.append(n - c)
	b.sort()
	e = -1
	m = len(b)
	for j in range(m):
		f = n - (m - j) * b[j]
		if e == -1:
			e = f
		else:
			e = min(e, f)
	if e == -1:
		print(0)
	else:
		print(e)


from collections import Counter
from math import inf
cases = int(input())
for _ in range(cases):
	n = int(input())
	arr = [int(i) for i in input().strip().split()]
	count = Counter(arr)
	vals = count.values()
	valCount = Counter(vals)

	def get(x):
		ans = 0
		for v in vals:
			if v >= x:
				ans += v - x
			else:
				ans += v
		return ans
	ans = inf
	for v in valCount.keys():
		ans = min(ans, get(v))
	print(ans)


for _ in ' ' * int(input()):
	(n, l, d, m) = (input(), input().split(), {}, 1000000000.0)
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	for i in set(d.values()):
		x = 0
		for j in d.values():
			if j < i:
				x += j
			elif j > i:
				x += j - i
		m = min(x, m)
	print(m)


from collections import *
C = Counter
for S in [*open(0)][2::2]:
	l = S.split()
	z = s = len(l)
	c = 0
	for (x, y) in sorted(C(C(l).values()).items())[::-1]:
		c += y
		z = min(z, s - c * x)
	print(z)


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj

def sieve():
	li = [True] * (10 ** 3 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	(prime, cur) = ([0] * 200, 0)
	for i in range(10 ** 3 + 5):
		if li[i] == True:
			prime[cur] = i
			cur += 1
	return prime

def SPF():
	mx = 10 ** 6 + 1
	spf[1] = 1
	for i in range(2, mx):
		if spf[i] == 1000000000.0:
			spf[i] = i
			for j in range(i * i, mx, i):
				if i < spf[j]:
					spf[j] = i
	return

def prime(n, d):
	prm = set()
	while n != 1:
		prm.add(spf[n])
		n = n // spf[n]
	for ele in prm:
		d[ele] = d.get(ele, 0) + 1
	return
mod = 998244353
inf = 10000000000000000

def solve():
	n = II()
	a = L()
	d = {}
	for ele in a:
		d[ele] = d.get(ele, 0) + 1
	freq = {}
	for ele in d:
		freq[d[ele]] = freq.get(d[ele], 0) + 1
	b = []
	for ele in freq:
		b.append([ele, freq[ele]])
	sm = n
	b.sort()
	ans = 100000000
	m = len(b)
	add = 0
	for i in range(m - 1, -1, -1):
		cur = b[i][0] * (b[i][1] + add)
		ans = min(ans, sm - cur)
		add += b[i][1]
	print(ans)
	return
t = II()
for i in range(t):
	solve()


import sys
input = sys.stdin.readline
from collections import Counter
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	C = Counter(A)
	LIST = [0] * (n + 3)
	for c in C.values():
		LIST[c] += 1
	S = [0] * (n + 3)
	for i in range(n + 3):
		S[i] = S[i - 1] + LIST[i]
	S2 = [0] * (n + 3)
	for i in range(n + 3):
		S2[i] = S2[i - 1] + LIST[i] * i
	ANS = 1 << 60
	for i in range(n + 3):
		if LIST[i] != 0:
			ANS = min(ANS, S2[i - 1] + S2[-1] - S2[i] - (S[-1] - S[i]) * i)
	print(ANS)


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	cnt = [0] * (n + 1)
	i = 0
	j = 0
	while i < n:
		while j < n and a[i] == a[j]:
			j += 1
			cnt[j - i] += j - i
		i = j
	ans = 0
	for i in range(n + 1):
		ans = max(ans, cnt[i])
	print(n - ans)


import sys
import math
import collections
import bisect
import itertools
import decimal
import heapq
INF = 10 ** 20
MOD = 10 ** 9 + 7

def ni():
	return int(sys.stdin.buffer.readline())

def ns():
	return map(int, sys.stdin.buffer.readline().split())

def na():
	return list(map(int, sys.stdin.buffer.readline().split()))

def na1():
	return list(map(lambda x: int(x) - 1, sys.stdin.buffer.readline().split()))

def flush():
	return sys.stdout.flush()

def nicf():
	return int(sys.stdin.readline())

def nscf():
	return map(int, sys.stdin.readline().split())

def nacf():
	return list(map(int, sys.stdin.readline().split()))

def na1cf():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))
tri = {i ** 3 for i in range(1, 10 ** 4 + 1)}

def solve():
	n = ni()
	a = na()
	cntd = collections.Counter(a)
	sumgroup = 0
	cnt = collections.defaultdict(int)
	for (k, v) in cntd.items():
		cnt[v] += 1
		sumgroup += 1
	done = 0
	ans = INF
	for k in sorted(cnt.keys()):
		v = cnt[k]
		sumgroup -= v
		tans = n - (v * k + k * sumgroup)
		ans = min(ans, tans)
	print(ans)

def main():
	t = ni()
	for ti in range(t):
		solve()
main()


t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split()))
	mx = 0
	cnt = {}
	g = [0] * (n + 1)
	ans = n
	for x in a:
		if x in cnt:
			cnt[x] = cnt[x] + 1
		else:
			cnt[x] = 1
		g[cnt[x]] = g[cnt[x]] + 1
		ans = min(ans, n - g[cnt[x]] * cnt[x])
	print(ans)


t = int(input())
for q in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	cnt = {}
	for i in a:
		if i not in cnt:
			cnt[i] = 1
		else:
			cnt[i] += 1
	counts = cnt.values()
	n_cnt = {}
	for i in counts:
		if i not in n_cnt:
			n_cnt[i] = 1
		else:
			n_cnt[i] += 1
	keys = sorted(n_cnt.keys())
	values = [n_cnt[x] for x in keys]
	sum_arr = [x * n_cnt[x] for x in keys]
	s = sum(sum_arr)
	min_score = s
	for (i, j) in enumerate(keys):
		score = s - j * n_cnt[j] - j * sum(values[i + 1:])
		if min_score > score:
			min_score = score
	print(min_score)


import math
import heapq

def S():
	return input()

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

def I():
	return int(S())

def L():
	return list(M())
for _ in range(I()):
	n = I()
	l = L()
	(di, d) = ({}, {})
	c = 0
	for i in range(n):
		di[l[i]] = di.get(l[i], 0) + 1
		d[di[l[i]]] = d.get(di[l[i]], 0) + 1
	m = -1
	for k in d:
		if k * d[k] > m:
			m = k * d[k]
	print(n - m)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ctr = {}
	for i in a:
		ctr[i] = ctr.get(i, 0) + 1
	borders = set([j for (i, j) in ctr.items()])
	best = 10 ** 9
	for bord in borders:
		cur = 0
		for (i, j) in ctr.items():
			if j < bord:
				cur += j
			else:
				cur += j - bord
		best = min(best, cur)
	print(best)


import math
numero_casos = int(input(''))
for i in range(numero_casos):
	n = int(input(''))
	numeros = list(input('').split(' '))
	mapa = dict()
	for i in range(n):
		if numeros[i] in mapa:
			mapa[numeros[i]] += 1
		else:
			mapa[numeros[i]] = 1
	mapa_ordenado = dict(sorted(mapa.items(), key=lambda x: x[1], reverse=True))
	indice = 0
	sup = 0
	infe = n
	toret = n + 1
	for (key, value) in mapa_ordenado.items():
		infe = infe - value
		toret = min(toret, infe + sup - indice * value)
		sup = sup + value
		indice += 1
	print(toret)


def solve():
	_ = int(input())
	a = list(map(int, input().split()))
	f = {}
	for x in a:
		if x in f:
			f[x] += 1
		else:
			f[x] = 1
	d = list(f.values())
	d.sort()
	n = len(d)
	p = [0 for i in range(n + 1)]
	for i in range(1, n + 1):
		p[i] = p[i - 1] + d[i - 1]
	s = p[n]
	for i in range(n):
		s = min(s, p[i] + p[n] - p[i + 1] - d[i] * (n - i - 1))
	print(s)
tests = int(input())
for test in range(tests):
	solve()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	args = list(map(int, input().split()))
	args.sort()
	occurs = []
	cnt = 0
	cur = -1
	args.append(-1)
	for arg in args:
		if cur != arg:
			cur = arg
			occurs.append(cnt)
			cnt = 0
		cnt += 1
	occurs.sort()
	occurs_occurs = []
	cnt = 0
	cur = -1
	occurs.append(-1)
	for occur in occurs:
		if cur != occur:
			occurs_occurs.append((cur, cnt))
			cur = occur
			cnt = 0
		cnt += 1
	mn = 987654321
	for i in range(2, len(occurs_occurs)):
		ans = 0
		for j in range(2, len(occurs_occurs)):
			if occurs_occurs[i][0] > occurs_occurs[j][0]:
				ans += occurs_occurs[j][1] * occurs_occurs[j][0]
			else:
				ans += occurs_occurs[j][1] * (occurs_occurs[j][0] - occurs_occurs[i][0])
		if ans < mn:
			mn = ans
	print(mn)


import sys
from collections import Counter
from itertools import accumulate
from bisect import bisect_right, bisect_left
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def solve():
	n = int(input())
	A = list(map(int, input().split()))
	D = Counter(A)
	cnt = [v for v in D.values()]
	cnt.sort()
	cnt_acc = [0] + list(accumulate(cnt))
	res = cnt_acc[-1]
	for num in set(cnt):
		l = bisect_left(cnt, num)
		r = bisect_right(cnt, num)
		tmp = cnt_acc[r] - (r - l) * num
		tmp += cnt_acc[-1] - cnt_acc[r] - num * (len(cnt) - r)
		res = min(res, tmp)
	print(res)

def resolve():
	t = int(input())
	for _ in range(t):
		solve()
resolve()


for _ in [*open(0)][2::2]:
	a = [*_.split()]
	q = {}
	for i in a:
		q[i] = q.get(i, 0) + 1
	w = sorted([*q.values()])
	q = 0
	o = len(w)
	for i in range(o):
		q = max(q, (o - i) * w[i])
	print(sum(w) - q)


def solve(n, A):
	freq = {}
	for a in A:
		freq[a] = freq.get(a, 0) + 1
	freq = {k: f for (k, f) in sorted(freq.items(), key=lambda item: item[1])}
	freqLength = len(freq)
	minRemoval = n
	i = 0
	for (k, f) in freq.items():
		minRemoval = min(n - (freqLength - i) * f, minRemoval)
		i += 1
	return minRemoval
for tc in range(int(input())):
	print(solve(int(input()), list(map(int, input().split()))))


total_case = int(input())
for t in range(total_case):
	n = int(input())
	nums = [int(x) for x in input().rstrip().split()]
	freq = {}
	for x in nums:
		if x in freq:
			freq[x] += 1
		else:
			freq[x] = 1
	snums = sorted((freq[x] for x in freq))
	n = len(snums)
	cumsum = [0] * n
	cumsum[0] = snums[0]
	for i in range(1, n):
		cumsum[i] = cumsum[i - 1] + snums[i]
	minremove = cumsum[-1] - snums[0] * n
	for i in range(1, n):
		if snums[i - 1] == snums[i]:
			continue
		remove = cumsum[-1] - snums[i] * (n - i)
		minremove = min(minremove, remove)
	print(minremove)


import sys
input = sys.stdin.readline
from collections import deque, defaultdict, Counter
from math import log10, ceil, factorial as F
inf = int(10000000000.0)
I = lambda : int(input())
L = lambda : list(map(int, input().split()))
T = lambda : map(int, input().split())
for _ in range(I()):
	n = I()
	lis = sorted(Counter(L()).values())
	n = len(lis)
	presum = [0] * (n + 1)
	for i in range(n):
		presum[i + 1] = presum[i] + lis[i]
	ans = inf
	i = 0
	while i < n:
		before = presum[i]
		after = presum[n] - presum[i + 1] - lis[i] * (n - i - 1)
		ans = min(ans, before + after)
		while i < n - 1 and lis[i] == lis[i + 1]:
			i += 1
		i += 1
	print(ans)


import sys
input = sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left
import math
from operator import itemgetter
from heapq import heapify, heappop, heappush
from queue import PriorityQueue as pq
for _ in range(int(input())):
	n = int(input())
	l = sorted(list(map(int, input().split())))
	x = dc(int)
	for i in l:
		x[i] += 1
	p = list(sorted(x.values()))
	x = dc(int)
	n = 0
	for i in p:
		x[i] += 1
		n += 1
	a = [0] * n
	b = [0] * n
	(a[0], b[-1]) = (p[0], p[-1])
	for i in range(1, n):
		a[i] = a[i - 1] + p[i]
	for i in range(n - 2, -1, -1):
		b[i] = b[i + 1] + p[i]
	m = sys.maxsize
	i = 0
	while i < n:
		c = 0
		if i != n - 1:
			t = i + x[p[i]]
			if t < n:
				c += b[t] - p[i] * (n - t)
		if i != 0:
			c += a[i - 1]
		m = min(m, c)
		i += x[p[i]]
	print(m)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	f = {}
	for i in d:
		f[d[i]] = f.get(d[i], 0) + 1
	m = -1
	v = -1
	for i in f:
		if f[i] > m:
			m = f[i]
			v = i
	ans = float('inf')
	for i in f:
		temp = 0
		for j in f:
			if j < i:
				temp += f[j] * j
			else:
				temp += (j - i) * f[j]
		ans = min(ans, temp)
	print(ans)


import sys
from collections import deque
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
li = lambda : list(input_())
pr = lambda x: print(x)
f = lambda : sys.stdout.flush()
for _ in range(ii()):
	n = ii()
	a = il()
	e = {}
	for i in range(n):
		if e.get(a[i]):
			e[a[i]] += 1
		else:
			e[a[i]] = 1
	d = []
	for i in e:
		d.append(e[i])
	x = sum(d)
	t = 0
	d.sort(reverse=True)
	m = float('inf')
	for i in range(len(d)):
		t += d[i]
		m = min(m, x - t + (t - (i + 1) * d[i]))
	print(m)


__version__ = '0.2'
__date__ = '2021-03-13'
import sys
from collections import Counter

def solve(n, a):
	a_counts = Counter(a)
	size = a_counts.most_common()[0][1]
	c_counts = [0] * (size + 1)
	for v in a_counts.values():
		c_counts[v] += 1
	for i in reversed(range(1, size)):
		c_counts[i] += c_counts[i + 1]
	for i in range(1, size + 1):
		c_counts[i] = i * c_counts[i]
	return n - max(c_counts)

def main(argv=None):
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		print(solve(n, a))
	return 0
STATUS = main()
sys.exit(STATUS)


for _ in range(int(input())):
	n = int(input())
	C = dict()
	for x in map(int, input().split()):
		if x in C:
			C[x] += 1
		else:
			C[x] = 1
	A = list(C.values())
	A.sort()
	sum = 0
	ans = n
	for i in range(len(A)):
		ans = min(ans, n - (len(A) - i) * A[i])
	print(ans)


import sys
zz = 1
sys.setrecursionlimit(10 ** 5)
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def ii():
	return input().rstrip()

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def dadd(d, p, val):
	if p in d:
		d[p].append(val)
	else:
		d[p] = [val]

def gi():
	return [xx for xx in input().split()]

def gtc(tc, ans):
	print('Case #' + str(tc) + ':', ans)

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

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

def gh():
	sys.stdout.flush()

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
uu = t
while t > 0:
	t -= 1
	n = fi()
	a = li()
	d = {}
	for i in a:
		inc(d, i)
	ans = 10 ** 18
	r = []
	for i in d:
		r.append(d[i])
	r.sort()
	pre = [0]
	for i in r:
		pre.append(pre[-1] + i)
	for i in range(len(r)):
		c = pre[i]
		w = pre[-1] - pre[i + 1]
		p = len(r) - i - 1
		c += w - r[i] * p
		ans = min(ans, c)
	print(ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ind = defaultdict(int)
	freq = [0] * (n + 1)
	for i in range(n):
		ind[l[i]] += 1
	for i in ind:
		freq[ind[i]] += 1
	s = SegmentTree(freq)
	freq1 = []
	for i in range(n + 1):
		freq1.append(i * freq[i])
	s1 = SegmentTree(freq1)
	fi = n
	for i in range(1, n + 1):
		ans = s1.query(0, i - 1) + s1.query(i + 1, n) - i * s.query(i + 1, n)
		fi = min(ans, fi)
	print(fi)


import math
import time
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
import sys
from heapq import heapify, heappush, heappop
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, stdin.readline().split()))
	c = Counter(a)
	cc = defaultdict(lambda : 0)
	for i in c.keys():
		cc[c[i]] += 1
	s = 0
	ans = math.inf
	tode = 0
	l = list(cc.keys())
	l.sort()
	for i in range(len(l)):
		temp = s
		for j in range(i + 1, len(l)):
			temp += (l[j] - l[i]) * cc[l[j]]
		ans = min(ans, temp)
		s += l[i] * cc[l[i]]
	print(ans)


import logging
import sys
from collections import Counter
from inspect import currentframe
input = sys.stdin.readline
logging.basicConfig(level=logging.DEBUG)

def dbg(*args):
	id2names = {id(v): k for (k, v) in currentframe().f_back.f_locals.items()}
	logging.debug(', '.join((id2names.get(id(arg), '???') + ' = ' + repr(arg) for arg in args)))

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	c = Counter(a)
	l = list(c.values())
	cc = Counter(l)
	cand_C = list(cc.keys())
	ans = float('inf')
	for C in cand_C:
		temp = 0
		for (k, v) in cc.items():
			if k > C:
				temp += (k - C) * v
			elif k < C:
				temp += k * v
		ans = min(ans, temp)
	print(ans)

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


import sys
from collections import Counter, defaultdict

def load_sys():
	return sys.stdin.readlines()

def load_local():
	with open('input.txt', 'r') as f:
		input = f.readlines()
	return input

def f(n, arr):
	arr = Counter(arr)
	freq = defaultdict(int)
	for x in arr:
		freq[arr[x]] += 1
	freq = list(freq.items())
	freq.sort(key=lambda x: x[0])
	s = 0
	ans = float('inf')
	for (f, dn) in freq[::-1]:
		ans = min(ans, n - f * dn - f * s)
		s += dn
	return ans
input = load_sys()
for i in range(1, len(input), 2):
	n = int(input[i])
	arr = [int(x) for x in input[i + 1].split()]
	print(f(n, arr))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	for n in l:
		if n not in d:
			d[n] = 1
		else:
			d[n] += 1
	e = sorted(list(d.values()))
	s = sum(e)
	print(min((s - (len(e) - i) * e[i] for i in range(len(e)))))


import sys
input = sys.stdin.readline
from collections import Counter
from itertools import accumulate
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = Counter()
	for i in a:
		c[i] += 1
	l = sorted(c.values())
	pref_sum = [0] + list(accumulate(l, lambda x, y: x + y))
	ans = float('inf')
	m = len(l)
	for i in range(1, m + 1):
		ans = min(ans, pref_sum[i - 1] + (pref_sum[m] - pref_sum[i] - (m - i) * l[i - 1]))
	print(ans)


T = int(input())
for _ in range(T):
	input()
	numbers = [int(x) for x in input().split()]
	counts = {}
	for x in numbers:
		try:
			counts[x] += 1
		except KeyError:
			counts[x] = 1
	counts = [0] + [value for (_, value) in counts.items()]
	counts = sorted(counts)
	lhs = 0
	rhs = sum(counts)
	min_tot = lhs + rhs
	for (i, x) in enumerate(counts[1:]):
		diff = x - counts[i]
		lhs += counts[i]
		rhs -= (len(counts) - i - 1) * diff
		if rhs + lhs < min_tot:
			min_tot = rhs + lhs
	print(min_tot)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	d = {}
	for num in a:
		d[num] = d.get(num, 0) + 1
	a = sorted([y for (x, y) in d.items()])
	left_items = n
	k = len(a)
	ans = 2e+18
	removed_items = 0
	for i in range(len(a)):
		ans = min(ans, removed_items + left_items - (k - i) * a[i])
		left_items -= a[i]
		removed_items += a[i]
	print(ans)


from collections import Counter

def equalize(arr):
	x = Counter(arr)
	lst = list(x.values())
	cnts = Counter(lst)
	ans = float('inf')
	for v in cnts.keys():
		temp = 0
		for i in cnts.keys():
			if i >= v:
				t = i - v
			else:
				t = i
			temp += t * cnts[i]
		ans = min(temp, ans)
	return ans
for i in range(int(input())):
	a = input()
	lst = list(map(int, input().strip().split()))
	print(equalize(lst))


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = Counter(l)
	x = list(d.values())
	x.sort()
	y = x.copy()
	for i in range(1, len(x)):
		x[i] += x[i - 1]
	ans = 9999999999
	for i in range(len(x)):
		p = x[i] - y[i] + x[len(x) - 1] - x[i] - y[i] * (len(x) - 1 - i)
		ans = min(ans, p)
	print(ans)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	occ = []
	occ = list(Counter(l).values())
	occ.sort()
	size = len(occ)
	behind = [0] * size
	s = 0
	i = 0
	while i < size:
		cur = occ[i]
		add = 0
		while i < size and cur == occ[i]:
			behind[i] = s
			add += occ[i]
			i += 1
		s += add
	sum_ahead = [0] * size
	ahead_sum = 0
	i = size - 1
	while i >= 0:
		freq = size - 1 - i
		cur_ans = ahead_sum - freq * occ[i]
		sum_add = 0
		cur = occ[i]
		while i >= 0 and cur == occ[i]:
			sum_add += occ[i]
			sum_ahead[i] = cur_ans
			i -= 1
		ahead_sum += sum_add
	ans = float('inf')
	for i in range(size):
		ans = min(ans, sum_ahead[i] + behind[i])
	print(ans)


in_length = int(input())
final_ouput = []
for i in range(in_length):
	length = int(input())
	inputs = input().split()
	input_dict = dict()
	for inp in inputs:
		if not inp in input_dict:
			input_dict.update([(inp, 1)])
		else:
			input_dict[inp] += 1
	amt_dict = dict()
	for val in input_dict.values():
		if not val in amt_dict:
			amt_dict.update([(val, 1)])
		else:
			amt_dict[val] += 1
	sorted_amts = sorted(amt_dict.keys())
	amt_amts = [amt_dict[amt] for amt in sorted_amts]
	acc_sum = 0
	min_val = length
	for (idx, amt) in enumerate(amt_amts):
		acc_sum += amt_amts[-1 - idx]
		interm_val = length - acc_sum * int(sorted_amts[-1 - idx])
		if interm_val < min_val:
			min_val = interm_val
	final_ouput.append(min_val)
for out in final_ouput:
	print(out)


for _ in ' ' * int(input()):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = 1
		else:
			d[a[i]] += 1
	s = 0
	m = float('inf')
	for i in set(d.values()):
		s = 0
		for j in d.values():
			if j > i:
				s += j - i
			elif i > j:
				s += j
		m = min(m, s)
	print(m)


import sys, threading, heapq, math
from collections import defaultdict, Counter
input = sys.stdin.readline

def main():
	for _ in range(int(input())):
		n = int(input())
		nums = list(map(int, input().split()))
		freq = defaultdict(int)
		for num in nums:
			freq[num] += 1
		freqGroup = defaultdict(int)
		for key in freq.keys():
			freqGroup[freq[key]] += 1
		freqKeys = sorted((key for key in freqGroup))
		cost1 = [0] * len(freqKeys)
		prev = freqKeys[0] * freqGroup[freqKeys[0]]
		for i in range(1, len(freqKeys)):
			cost1[i] = cost1[i - 1] + prev
			prev = freqKeys[i] * freqGroup[freqKeys[i]]
		cost2 = [0] * len(freqKeys)
		prev = freqGroup[freqKeys[-1]]
		for i in range(len(freqKeys) - 2, -1, -1):
			cost2[i] += (freqKeys[i + 1] - freqKeys[i]) * prev + cost2[i + 1]
			prev += freqGroup[freqKeys[i]]
		ans = math.inf
		for i in range(len(freqKeys)):
			ans = min(ans, cost1[i] + cost2[i])
		print(ans)
main()


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	a = sorted(map(int, input().split()))
	i = 0
	b = []
	while i < n:
		c = a[i]
		j = i + 1
		while j < n and a[j] == c:
			j += 1
		b.append(j - i)
		i = j
	b.sort()
	res = n
	s = 0
	z = 0
	left = n
	for i in range(len(b) - 1, -1, -1):
		s += b[i]
		z += 1
		left -= b[i]
		can = s - b[i] * z + left
		res = min(res, can)
	print(res)
for i in range(int(input())):
	solve()


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	a.append(-1)
	count = 1
	stored = [0 for i in range(n + 5)]
	for i in range(n):
		if a[i] == a[i + 1]:
			count += 1
		else:
			stored[count] += 1
			count = 1
	stored1 = stored[:]
	stored2 = stored[:]
	stored3 = [0 for i in range(n + 5)]
	for i in range(n - 1, -1, -1):
		stored1[i] += stored1[i + 1]
		stored3[i] = stored1[i + 1] + stored3[i + 1]
	for i in range(1, n):
		stored2[i] = stored2[i] * i + stored2[i - 1]
	mini = 10000000000000
	for i in range(1, n + 1):
		mini = min(stored3[i] + stored2[i - 1], mini)
	print(mini)


def equalizeTheArray(a):
	d = dict()
	for i in range(len(a)):
		if str(a[i]) in d.keys():
			d[str(a[i])] += 1
		else:
			d[str(a[i])] = 1
	k = sorted(list(d.values()))
	s = sum(k)
	n = len(k)
	c = [s - (n - i) * k[i] for i in range(n)]
	return min(c)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	print(equalizeTheArray(a))


import io
import os
import math
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	d = {}
	a = [int(x) for x in input().split()]
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = 0
		d[a[i]] += 1
	ans = []
	for x in d:
		ans.append(d[x])
	ans.sort()
	temp = 0
	tt = len(ans)
	b = sum(ans)
	mim = 1000000000.0
	for i in range(tt):
		temp = b - ans[i] * (tt - i)
		mim = min(temp, mim)
	print(mim)


from collections import Counter

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	cnt_obj = Counter(Counter(a).values())
	cnt = [cnt_obj[i] for i in range(n + 2)]
	left = [0] * (n + 2)
	right = [0] * (n + 2)
	for i in range(1, n + 1):
		left[i] = left[i - 1] + i * cnt[i]
	c = 0
	for i in range(n, 0, -1):
		right[i] = right[i + 1] + c
		c += cnt[i]
	res = n
	for i in range(n, 0, -1):
		res = min(res, left[i - 1] + right[i])
	print(res)
t = int(input())
for _ in range(t):
	solve()


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	cnt = defaultdict(int)
	for i in arr:
		cnt[i] += 1
	dp = [0 for i in range(n + 1)]
	for k in cnt.values():
		dp[k] += 1
	suff = [0 for i in range(n + 1)]
	mul = [0 for i in range(n + 1)]
	suff[-1] = dp[-1]
	mul[-1] = n * dp[-1]
	for i in range(n - 1, 0, -1):
		suff[i] = dp[i] + suff[i + 1]
		mul[i] = dp[i] * i + mul[i + 1]
	ans = float('inf')
	prev = 0
	for i in range(1, n + 1):
		if i + 1 < n + 1:
			temp = max(0, mul[i + 1] - suff[i + 1] * i)
		else:
			temp = 0
		ans = min(ans, prev + temp)
		prev += dp[i] * i
	print(ans)


test = int(input())

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	cnt = dict()
	for i in a:
		if cnt.get(i) == None:
			cnt[i] = 1
		else:
			cnt[i] += 1
	val = list(cnt.values())
	val.sort()
	ans = 10 ** 9
	_sum = 0
	for i in range(len(val)):
		res = n - val[i] * (len(val) - i)
		ans = min(ans, res)
	print(ans)
for i in range(test):
	solve()


import sys
import collections

def solve(n, a):
	counter = collections.Counter()
	for elem in a:
		counter[elem] += 1
	counts = sorted(counter.values())
	lessers_to_delete = dict()
	value = 0
	for elem in counts:
		if elem not in lessers_to_delete:
			lessers_to_delete[elem] = value
		value += elem
	value = counts[-1]
	count = 1
	greatter_to_delete = dict()
	greatter_to_delete[value] = 0
	for i in range(len(counts) - 2, -1, -1):
		elem = counts[i]
		if elem != value:
			greatter_to_delete[elem] = greatter_to_delete[value] + count * (value - elem)
			value = elem
		count += 1
	return min((greatter_to_delete[i] + lessers_to_delete[i] for i in set(counts)))

def main():
	res = ''
	input = sys.stdin.readline
	print = sys.stdout.write
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		res += str(solve(n, a)) + '\n'
	print(res)
main()


I = input
IN = lambda x: map(int, x.split())
L = lambda x: list(IN(x))
for _ in range(int(I())):
	n = int(I())
	a = L(I())
	d = {}
	f = {}
	c = 0
	for i in a:
		t = d.get(i, 0) + 1
		d[i] = t
		f[t] = f.get(t, 0) + 1
	max = 0
	for (x, y) in f.items():
		t = x * y
		if t > max:
			max = t
	print(n - max)


import collections, bisect
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = n
	cs = collections.Counter(arr)
	cv = list(cs.values())
	cv.sort()
	sv = [0]
	s = 0
	for c in cv:
		s += c
		sv.append(s)
	for t in set(cv):
		p = 0
		i = bisect.bisect_left(cv, t)
		p += sv[i]
		j = bisect.bisect_right(cv, t)
		p += sv[-1] - sv[j] - t * (len(cv) - j)
		ans = min(ans, p)
	print(ans)


def solve(arr, n, ans):
	counts = {}
	for i in arr:
		if i not in counts.keys():
			counts[i] = 0
		counts[i] += 1
	arr = []
	for i in counts.keys():
		arr.append(counts[i])
	min_val = float('inf')
	arr.sort()
	prev = 0
	for i in range(len(arr)):
		x = arr[i]
		rem = n - prev - arr[i]
		min_val = min(min_val, prev + rem - x * (len(arr) - i - 1))
		prev += arr[i]
	ans.append(str(min_val))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(arr, n, ans)
	print('\n'.join(ans))
main()


for _ in range(int(input())):
	n = int(input())
	arr = (*map(int, input().split()),)
	freq = {}
	for num in arr:
		freq[num] = freq.get(num, 0) + 1
	ff = {}
	for occ in freq.values():
		ff[occ] = ff.get(occ, 0) + 1
	last = 0
	ans = n + 1
	for occ in sorted(ff.keys(), reverse=True):
		ff[occ] = ff[occ] + last
		last = ff[occ]
		volume = ff[occ] * occ
		ans = min(ans, n - volume)
	print(ans)


from collections import Counter, defaultdict
import bisect

def solve(a):
	c = Counter(a)
	values = sorted(c.values())
	prefix_sum = defaultdict(int)
	prefix_sum[-1] = 0
	prefix_sum[0] = values[0]
	for i in range(1, len(values)):
		prefix_sum[i] = prefix_sum[i - 1] + values[i]
	cache = dict()

	def get_cost(C):
		if C in cache:
			return cache[C]
		l = bisect.bisect_left(values, C) - 1
		r = bisect.bisect_right(values, C) - 1
		remove_left_cost = prefix_sum[l]
		remove_right_cost = prefix_sum[len(values) - 1] - prefix_sum[r] - C * (len(values) - 1 - r)
		cost = remove_left_cost + remove_right_cost
		cache[C] = cost
		return cost
	ans = min(map(get_cost, values))
	print(ans)
num_tests = int(input())
for _ in range(num_tests):
	poop = int(input())
	solve(list(map(int, input().split())))


from collections import Counter
tc = int(input())
for _ in range(tc):
	n = int(input())
	count = Counter(map(int, input().split()))
	total = float('inf')
	common = count.items()
	(_, num) = zip(*common)
	num = list(num)
	test = Counter(num)
	for x in test:
		ret = 0
		for x1 in test:
			if x > x1:
				ret += x1 * test[x1]
			else:
				ret += (x1 - x) * test[x1]
		total = min(total, ret)
	print(total)


import sys

def main():
	pass

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def lts(l):
	s = ''.join(map(str, l))
	return s

def stl(s):
	l = list(s)
	return l

def sq(a, target, arr=[]):
	s = sum(arr)
	if s == target:
		return arr
	if s >= target:
		return
	for i in range(len(a)):
		n = a[i]
		remaining = a[i + 1:]
		ans = sq(remaining, target, arr + [n])
		if ans:
			return ans

def SieveOfEratosthenes(n):
	cnt = 0
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			cnt += 1
	return cnt

def nCr(n, r):
	f = math.factorial
	return f(n) // f(r) // f(n - r)
mod = int(1000000000.0) + 7

def ssinp():
	return sys.stdin.readline().strip()

def iinp():
	return int(input())

def nninp():
	return map(int, sys.stdin.readline().strip().split())

def llinp():
	return list(map(int, sys.stdin.readline().strip().split()))

def p(xyz):
	print(xyz)

def p2(a, b):
	print(a, b)
import math
from collections import OrderedDict
from fractions import Fraction
for __ in range(iinp()):
	n = iinp()
	a = llinp()
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	freq = {}
	for key in d:
		if d[key] in freq:
			freq[d[key]] += 1
		else:
			freq[d[key]] = 1
	ans = 18293123
	for i in freq:
		remove = 0
		ans1 = 0
		for j in freq:
			if j < i:
				remove = remove + freq[j] * j
			elif j > i:
				ans1 = ans1 + (j - i) * freq[j]
		ans = min(ans, ans1 + remove)
	p(ans)


from collections import Counter, defaultdict, OrderedDict, deque
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from typing import List
import itertools
import math
import heapq
import string
import random
(MIN, MAX, MOD) = (-1061109567, 1061109567, 1000000007)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = Counter(a)
	a = sorted(c.values())
	nums = list(itertools.accumulate(a))
	i = 0
	ans = n
	n = len(a)
	while i < n:
		idx = bisect_right(a, a[i])
		if idx >= n:
			ans = min(ans, nums[i] - a[i])
			break
		if idx >= n or i >= n or i < 0 or (idx < 0):
			break
		total = nums[i - 1] if i > 0 else 0
		total += nums[-1] - nums[idx] + a[idx] - a[i] * (n - idx)
		ans = min(ans, total)
		i = idx
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = defaultdict(int)
	for x in a:
		d[x] += 1
	c = sorted(list(d.values()))
	csum = sum(c)
	t = 0
	m = len(c)
	ans = None
	for (i, x) in enumerate(c):
		ca = csum - x * (m - i) + t
		if ans is None or ans > ca:
			ans = ca
		t += x
		csum -= x
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	dic = {}
	for el in a:
		if el in dic:
			dic[el] += 1
		else:
			dic[el] = 1
	mini = 99999999999999
	s = set()
	for el in dic.values():
		if el not in s:
			s.add(el)
	w = {}
	for el in dic:
		if dic[el] in w:
			w[dic[el]] += 1
		else:
			w[dic[el]] = 1
	for el in s:
		p = 0
		for o in w:
			if o > el:
				p += w[o] * (o - el)
			elif o < el:
				p += w[o] * o
		mini = min(mini, p)
	print(mini)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for n in a:
		if n not in d:
			d[n] = 0
		d[n] += 1
	c = list(d.values())
	c.sort()
	s = sum(c)
	ans = min([s - (len(c) - i) * c[i] for i in range(len(c))])
	print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def dijkstra(start, distance, path, n):
	visited = [False for _ in range(n)]
	distance[start] = 0
	for i in range(n):
		v = -1
		for j in range(n):
			if not visited[v] and (v == -1 or distance[j] < distance[v]):
				v = j
		if distance[v] == math.inf:
			break
		visited[v] = True
		for edge in adj[v]:
			destination = edge[0]
			weight = edge[1]
			if distance[v] + weight < distance[destination]:
				distance[destination] = distance[v] + weight
				path[destination] = v

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def lcm(a, b):
	return a * b // gcd(a, b)

def ncr(n, r):
	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)

def seive(n):
	primes = [True] * (n + 1)
	ans = []
	for i in range(2, n):
		if not primes[i]:
			continue
		j = 2 * i
		while j <= n:
			primes[j] = False
			j += i
	for p in range(2, n + 1):
		if primes[p]:
			ans += [p]
	return ans

def factors(n):
	factors = []
	x = 1
	while x * x <= n:
		if n % x == 0:
			if n // x == x:
				factors.append(x)
			else:
				factors.append(x)
				factors.append(n // x)
		x += 1
	return factors

def main():
	try:
		from collections import Counter
		for _ in range(inp()):
			n = inp()
			a = inlt()
			vals = sorted(Counter(a).values())
			size = len(vals)
			if len(set(vals)) == 1:
				print('0')
				continue
			pre = []
			suff = []
			(pc, sc) = (0, 0)
			for i in range(len(vals)):
				pc += vals[i]
				sc += vals[size - i - 1]
				pre += [pc]
				suff += [sc]
			ans = math.inf
			for i in range(len(vals)):
				if i > 0 and vals[i] == vals[i - 1]:
					continue
				if i == 0:
					result = suff[size - i - 2] - (size - i - 1) * vals[i]
				elif 0 < i < size - 1:
					result = suff[size - i - 2] - (size - i - 1) * vals[i] + pre[i - 1]
				elif i == size - 1:
					result = pre[i - 1]
				ans = min(result, ans)
			print(ans)
	except Exception as e:
		print(e)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import Counter
from sys import stdin

def solve(arr, n):
	c = Counter(arr)
	s = sorted(c.values(), reverse=True)
	res = n
	d = Counter(s)
	for i in range(s[0] + 1):
		tmp = 0
		for e in d.keys():
			if e >= i:
				tmp += (e - i) * d[e]
			else:
				tmp += e * d[e]
		res = min(res, tmp)
	return res

def main():
	t = int(stdin.readline())
	for i in range(t):
		n = int(stdin.readline())
		print(solve(list(map(int, stdin.readline().split(' '))), n))
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline()

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

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

def print_list(l):
	print(' '.join(map(str, l)))
from collections import Counter
for _ in range(N()):
	n = N()
	a = RLL()
	count = Counter(Counter(a).values())
	p = list(count.keys())
	p.sort(reverse=True)
	s = 0
	ans = n
	for k in p:
		s += count[k]
		ans = min(ans, n - k * s)
	print(ans)


__version__ = '1.0'
__date__ = '2021-03-13'
import sys
from collections import Counter

def solve(n, a):
	a_counts = Counter(a)
	c_counts = Counter(a_counts.values())
	carry = 0
	for (k, v) in sorted(c_counts.items(), reverse=True):
		c_counts[k] += carry
		carry += v
	(k, v) = max(c_counts.items(), key=lambda x: x[0] * x[1])
	return n - k * v

def main(argv=None):
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		print(solve(n, a))
	return 0
STATUS = main()
sys.exit(STATUS)


from collections import Counter

def get_min(times_dict):
	final_ans = 2 * 10 ** 14
	for times in set(times_dict):
		ans = 0
		for t in times_dict:
			if t >= times:
				ans += (t - times) * times_dict[t]
			else:
				ans += t * times_dict[t]
		final_ans = min(final_ans, ans)
	return final_ans
t = int(input())
for _ in range(t):
	n = int(input())
	a_list = list(map(int, input().split()))
	a_dict = Counter(a_list)
	times_dict = Counter(a_dict.values())
	get_ans = get_min(times_dict)
	print(get_ans)


from collections import Counter
for x in range(int(input())):
	n = int(input())
	m = list(map(int, input().split()))
	x = Counter(m)
	a = []
	for i in x:
		a.append(x[i])
	a.sort()
	mi = n + 1
	for (i, v) in enumerate(a):
		mi = min(mi, n - (len(a) - i) * v)
	print(mi)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	d = {}
	for i in a:
		if i in d.keys():
			d[i] += 1
		else:
			d[i] = 1
	d = sorted(d.values())
	ans = 10 ** 6
	size = len(d)
	ps = 0
	for i in range(len(d)):
		ans = min(ans, ps + n - size * d[i])
		n -= d[i]
		size -= 1
		ps += d[i]
	print(ans)


import sys
import math
input = sys.stdin.readline
mod = 10 ** 9 + 7

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
for _ in range(inp()):
	n = inp()
	l = inlt()
	l.sort()
	c = []
	s = 1
	if n == 1:
		print(0)
		continue
	for i in range(n - 1):
		if l[i] == l[i + 1]:
			s += 1
			if i == n - 2:
				c.append(s)
		else:
			c.append(s)
			s = 1
			if i == n - 2:
				c.append(1)
	c.sort()
	a = []
	b = 0
	for i in range(len(c)):
		b = b + c[i]
		a.append(b)
	out = []
	for i in range(len(c)):
		out.append(a[i] - c[i] + a[-1] - a[i] - (len(c) - i - 1) * c[i])
	print(min(out))


def bruteForce(n, arr):
	d = dict()
	for i in arr:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	group = dict()
	for i in d:
		if d[i] in group:
			group[d[i]].append(i)
		else:
			group[d[i]] = [i]
	ans = n
	for i in group:
		temp = 0
		for j in group:
			if i == j:
				continue
			elif j < i:
				temp += len(group[j]) * j
			else:
				temp += len(group[j]) * (j - i)
		ans = min(temp, ans)
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(bruteForce(n, arr))


from sys import stdin
input = stdin.buffer.readline
t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	d = {}
	for i in arr:
		if i in d:
			d[i] = d[i] + 1
		else:
			d[i] = 1
	ll = len(d)
	dd = {}
	for i in d.keys():
		if d[i] in dd:
			dd[d[i]] = dd[d[i]] + 1
		else:
			dd[d[i]] = 1
	l = []
	for key in dd.keys():
		l.append((key, dd[key]))
	l.sort()
	ans = n
	for i in l:
		ans = min(ans, n - ll * i[0])
		ll = ll - i[1]
	print(ans)


from collections import defaultdict
from bisect import bisect_right
for _ in ' ' * int(input()):
	n = int(input())
	(a, d, c, s, p, f) = (list(map(int, input().split())), defaultdict(int), defaultdict(int), 10 ** 10, [], [])
	for i in range(n):
		d[a[i]] += 1
	for i in d:
		c[d[i]] += 1
		p.append(d[i])
	x = sorted(c)
	p.sort()
	l = len(x)
	for i in range(l):
		f.append((f[i - 1] if i else 0) + x[i] * c[x[i]])
		s = min(s, n - f[i] - (len(p) - bisect_right(p, x[i])) * x[i] + (f[i - 1] if i else 0))
	print(s)


import collections
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	total = n
	min_removals = total
	previous = 0
	c = collections.Counter(collections.Counter(arr).values())
	current_count = sum(c.values())
	for k in sorted(c.keys()):
		current_cost = total - current_count * k
		min_removals = min(min_removals, current_cost)
		current_count -= c[k]
		previous += c[k] * k
	print(min_removals)


from collections import *
for t in range(int(input())):
	z = s = int(input())
	c = 0
	for (x, y) in sorted(Counter(Counter(input().split()).values()).items())[::-1]:
		c += y
		z = min(z, s - c * x)
	print(z)


N = int(input())
for i in range(N):
	n = int(input())
	x = list(map(int, input().split()))
	dct = {}
	for each in x:
		dct[each] = dct.get(each, 0) + 1
	rank = sorted(dct.values())
	(ret, ans) = (0, 0)
	for j in range(len(rank)):
		ret = (len(rank) - j) * rank[j]
		if ret > ans:
			ans = ret
	print(n - ans)


from collections import defaultdict
import bisect
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	d = defaultdict(lambda : 0)
	for i in range(n):
		d[A[i]] += 1
	l = list(d.values())
	l.sort()
	ans = 0
	t = len(l)
	for i in range(len(l)):
		ans = max(ans, l[i] * (t - i))
	print(n - ans)


from collections import Counter
num = int(input())
questions = list()
for i in range(num):
	length = input()
	li = [int(str) for str in input().split()]
	questions.append(li)
for question in questions:
	counter = Counter(question)
	times = [v[1] for v in counter.items()]
	times.sort()
	n = len(times)
	ans = sum(times) - n * times[0]
	temp = ans
	i = 0
	while i < n:
		plus = times[i]
		while i < n - 1 and times[i] == times[i + 1]:
			plus += times[i + 1]
			i += 1
		if i == n - 1:
			break
		minus = (n - 1 - i) * (times[i + 1] - times[i])
		temp = temp + plus - minus
		ans = min(ans, temp)
		i += 1
	print(ans)


from collections import *
for _ in [*open(0)][2::2]:
	w = sorted(Counter([*_.split()]).values())
	o = len(w)
	print(sum(w) - max(((o - i) * w[i] for i in range(o))))


for o in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	b = []
	cnt = 1
	for i in range(1, n):
		if a[i] == a[i - 1]:
			cnt += 1
		else:
			b.append(cnt)
			cnt = 1
	b.append(cnt)
	b.sort()
	s = sum(b)
	n = len(b)
	ans = [s - (n - i) * b[i] for i in range(n)]
	print(min(ans))


import math
import sys
from collections import *

def cint():
	return list(map(int, sys.stdin.readline().strip().split()))

def cstr():
	return list(map(str, input().split(' ')))

def solve():
	n = int(input())
	lst = cint()
	dct = {}
	for i in lst:
		if dct.get(i) is None:
			dct[i] = 1
		else:
			dct[i] += 1
	s = set()
	lst = []
	for k in dct:
		s.add(dct[k])
		lst.append(dct[k])
	ans = math.inf
	for c in s:
		temp = 0
		for i in lst:
			if i < c:
				temp += i
			else:
				temp += i - c
		if temp < ans:
			ans = temp
	print(ans)
t = int(input())
while t != 0:
	solve()
	t -= 1


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
from bisect import *

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		b = Counter(a)
		c = []
		for i in b:
			c.append(b[i])
		c.sort()
		mi = n + 1
		su = 0
		for i in range(len(c)):
			mi = min(mi, su + (n - su) - (len(c) - i) * c[i])
			su += c[i]
		print(mi)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import Counter, defaultdict

def main():
	cases = int(input())
	ans_list = []
	for _ in range(cases):
		n = int(input())
		a = list(map(int, input().split(' ')))
		c = Counter(a)
		d = defaultdict(int)
		for num in c:
			d[c[num]] += 1
		keys = sorted(list(d.keys()))[::-1]
		ans = float('inf')
		prev_op_cost = 0
		prev_count = 0
		prev_val = 10 ** 9
		go_to_zero_count = n
		for occ_count in keys:
			numbers_with_occ_count = d[occ_count]
			go_to_zero_count -= numbers_with_occ_count * occ_count
			prev_op_cost += (prev_val - occ_count) * prev_count
			ans = min(ans, go_to_zero_count + prev_op_cost)
			prev_val = occ_count
			prev_count += numbers_with_occ_count
		ans_list.append(ans)
	print('\n'.join(map(str, ans_list)))
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(cnt, occ) = ({}, {})
	le = 0
	n = int(input())
	for i in list(input().split()):
		if occ.get(i, None):
			occ[i] += 1
		else:
			occ[i] = 1
		if cnt.get(occ[i], None):
			cnt[occ[i]] += 1
		else:
			cnt[occ[i]] = 1
	mx = 0
	for i in cnt:
		if i * cnt[i] > mx:
			mx = i * cnt[i]
	print(n - mx)


t = int(input())
for i in range(t):
	n = int(input())
	li = list(map(int, input().split()))
	dic = {}
	for i in li:
		if i not in dic:
			dic[i] = 1
		else:
			dic[i] = dic[i] + 1
	val = list(dic.values())
	val.sort()
	l = len(val)
	ans = []
	for i in range(l - 1, -1, -1):
		if i == l - 1:
			ans.append(val[i])
		else:
			m = val[i] * (l - i)
			ans.append(m)
	m = n - max(ans)
	print(m)


import sys
YES = 'YES'
NO = 'NO'
MOD = 1000000007

def input_int():
	return int(input())

def input_list():
	return input().split(' ')

def input_list_int():
	return list(map(int, input_list()))

def solve():
	n = input_int()
	a = input_list_int()
	s = {}
	for i in range(0, n):
		if a[i] not in s:
			s[a[i]] = 0
		s[a[i]] += 1
	s = sorted(s.items(), key=lambda x: x[1])
	ss = {}
	for i in range(0, len(s)):
		if s[i][1] not in ss:
			ss[s[i][1]] = 0
		ss[s[i][1]] += 1
	res = n
	left = 0
	right = n
	rightCnt = len(s)
	for (key, val) in ss.items():
		res = min(res, left + right - rightCnt * key)
		left += key * val
		right -= key * val
		rightCnt -= val
	print(res)
query_count = input_int()
while query_count:
	query_count -= 1
	solve()


from collections import Counter
T = int(input())
for case in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	counter = Counter(a)
	arr = list(counter.values())
	arr.sort()
	presum = [0]
	for i in range(len(arr)):
		presum.append(presum[-1] + arr[i])
	ans = float('inf')
	m = len(arr)
	for i in range(m):
		temp = presum[i]
		temp += presum[m] - presum[i + 1] - arr[i] * (m - 1 - i)
		ans = min(ans, temp)
	print(ans)


t = int(input())
for _t in range(t):
	n = int(input())
	a = [int(p) for p in input().split()]
	m = {}
	for val in a:
		m[val] = 0
	for val in a:
		m[val] += 1
	arr = []
	for (k, v) in m.items():
		arr.append(v)
	arr.sort()
	summ = [0]
	for i in range(len(arr)):
		summ.append(summ[i] + arr[i])
	abs_k = 0
	res = 100000000000000000000
	for k in range(len(arr)):
		g_k = summ[len(arr)] - summ[k] - (len(arr) - k) * arr[k]
		if res > g_k + abs_k:
			res = g_k + abs_k
		abs_k += arr[k]
	print(res)


from collections import Counter
T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	count = list(Counter(A).values())
	secCount = Counter(count)
	ans = 10 ** 6
	for n in range(0, max(count) + 1):
		score = 0
		for (number, occur) in secCount.items():
			if number < n:
				score += occur * number
			else:
				score += occur * (number - n)
		ans = min(score, ans)
	print(ans)


T = int(input())
for testcase in range(1, T + 1):
	d = {}
	n = int(input())
	l = input().split(' ')
	a = [int(i) for i in l]
	for i in range(len(a)):
		if a[i] in d:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	x = list(d.values())
	x.sort()
	d2 = {}
	for i in range(len(x)):
		if x[i] in d2:
			d2[x[i]] += 1
		else:
			d2[x[i]] = 1
	l = list(d2.keys())
	l.sort()
	best = 10 ** 9
	for i in l:
		count = 0
		for j in l:
			if j < i:
				count += j * d2[j]
			elif j > i:
				count += (j - i) * d2[j]
		if count < best:
			best = count
	print(best)


t = int(input())
for i in range(t):
	ret = []
	freq_of_nums = {}
	n = int(input())
	arr = list(map(int, input().split()))
	for num in arr:
		if num not in freq_of_nums:
			freq_of_nums[num] = 1
		elif num in freq_of_nums:
			freq_of_nums[num] += 1
	ff = [0] * (n + 1)
	for val in freq_of_nums.values():
		ff[val] += 1
	ans = 0
	mc = 0
	for c in range(1, n + 1):
		ans = max(ans, c * (len(freq_of_nums) - mc))
		mc += ff[c]
	print(n - ans)


for rpt in range(int(input())):
	number_count = int(input())
	numbers = [int(x) for x in input().split()]
	occurence = {}
	for number in numbers:
		occurence[number] = 0
	for number in numbers:
		occurence[number] += 1
	occurences = []
	for number in occurence.values():
		occurences.append(number)
	occurences.sort(reverse=True)
	best = number_count
	left_sum = 0
	right_sum = number_count
	last_eliminated = occurences[0]
	index = 0
	while index < len(occurences):
		best = min(best, left_sum + right_sum)
		left_sum += index * (last_eliminated - occurences[index])
		right_sum -= occurences[index]
		last_eliminated = occurences[index]
		index += 1
	best = min(best, left_sum + right_sum)
	print(best)


from collections import defaultdict, Counter
from itertools import accumulate
import sys
input = sys.stdin.readline
inf = 100000000000000000
mod = 998244353
for CASES in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	C = Counter(A)
	LIST = [0] * (n + 2)
	for c in C.values():
		LIST[c] += 1
	presum = 0
	forsum = sum(LIST)
	LIST2 = [0] * (n + 2)
	for i in range(len(LIST2)):
		LIST2[i] = LIST[i] * i
	allsum = sum(LIST2)
	ans = 1 << 60
	for i in range(1, len(LIST)):
		presum += LIST[i - 1] * (i - 1)
		allsum -= forsum
		forsum -= LIST[i]
		ans = min(ans, presum + allsum)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		d = {}
		for i in a:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
		b = []
		for i in d:
			b.append(d[i])
		freq = []
		d = {}
		for i in b:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
		for i in d:
			freq.append([i, d[i]])
		freq.sort()
		suffsum = []
		curr = 0
		hav = 0
		total = 0
		for i in range(len(freq) - 1, -1, -1):
			hav += freq[i][1]
			total += freq[i][0] * freq[i][1]
		l = 0
		ans = float('inf')
		bef = 0
		for i in range(len(freq)):
			hav -= freq[i][1]
			total -= freq[i][0] * freq[i][1]
			while l < len(freq) and freq[l][0] < freq[i][0]:
				bef += freq[l][1] * freq[l][0]
				l += 1
			ans = min(ans, bef + total - hav * freq[i][0])
		print(ans)
	return
main()


def solve(d, occ):
	temp = 0
	for ele in d:
		if d[ele] > occ:
			temp += d[ele] - occ
		elif d[ele] < occ:
			temp += d[ele]
	return temp
for testcase in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	d = {}
	m = 1
	for ele in arr:
		if ele in d:
			d[ele] += 1
			m = max(m, d[ele])
		else:
			d[ele] = 1
	li = set()
	for ele in d:
		li.add(d[ele])
	ans = float('inf')
	for ele in li:
		ans = min(ans, solve(d, ele))
	print(ans)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

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

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().split(' ')

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	n = get_int()
	a = get_ints()
	k = 0
	for i in range(n - 1):
		A = max(a[i], a[i + 1])
		B = min(a[i], a[i + 1])
		while 2 * B < A:
			k += 1
			B *= 2
	return k

def solve_b():
	n = get_int()
	a = get_ints()
	rems = [x % 3 for x in a]
	count_rems = [rems.count(i) for i in range(3)]
	k = 0
	for repeat in range(2):
		for i in range(3):
			if count_rems[i] > n // 3:
				k += count_rems[i] - n // 3
				count_rems[(i + 1) % 3] += count_rems[i] - n // 3
				count_rems[i] = n // 3
	return k

def solve_c():
	cubes = set()
	i = 1
	while i ** 3 < 10 ** 12 + 1:
		cubes.add(i ** 3)
		i += 1

	def solve():
		x = get_int()
		j = 1
		while j ** 3 <= x:
			if x - j ** 3 in cubes:
				return 'YES'
			j += 1
		return 'NO'
	t = get_int()
	for _ in range(t):
		print(solve())

def solve_d():
	n = get_int()
	p = get_ints()
	dp = [-1] * n
	for i in range(n, 0, -1):
		X = p.index(i)
		m = -1
		for j in range(X, n):
			if dp[j] > -1:
				m = max(m, dp[j])
				break
		for j in range(X, -1, -1):
			if dp[j] > -1:
				m = max(m, dp[j])
				break
		dp[X] = m + 1
	res = {}
	return dp

def solve_e():
	n = get_int()
	a = get_ints()
	a_uniq = list(set(a))
	a_uniq.sort()
	a_count = Counter(a)

	def good(k):
		x = a_uniq[k]
		for i in range(len(a_uniq)):
			if x >= a_uniq[i]:
				x += a_uniq[i] * (a_count[a_uniq[i]] - int(i == k))
			else:
				return False
		return True
	L = -1
	R = len(a_uniq) - 1
	bs = binary_search(good, L, R, right_true=True)
	u = a_uniq[bs]
	res = []
	for i in range(n):
		if a[i] >= u:
			res.append(i + 1)
	return res

def solve_f():
	n = get_int()
	a = get_ints()
	C = Counter(a)
	candidates = set(C.values())
	S = float('inf')
	for cand in candidates:
		tmp = 0
		for k in C:
			if C[k] < cand:
				tmp += C[k]
			elif C[k] > cand:
				tmp += C[k] - cand
		S = min(S, tmp)
	return S
t = get_int()
for _ in range(t):
	print(solve_f())


import sys
import math
N = int(10000.0 + 5)
sys.setrecursionlimit(N)

def charming():
	n = int(input())
	a = [0] + list(map(int, input().split()))
	d1 = dict()
	d2 = dict()
	for i in range(1, n + 1):
		if a[i] not in d1:
			d1[a[i]] = 1
		else:
			d1[a[i]] += 1
	for i in d1.keys():
		if d1[i] not in d2:
			d2[d1[i]] = 1
		else:
			d2[d1[i]] += 1
	Sum = 0
	cnt = 0
	for i in d2.keys():
		Sum += i * d2[i]
		cnt += d2[i]
	res = Sum
	mx = 0
	keys = list(d2.keys())
	keys.sort()
	for i in keys:
		mx = max(mx, i * cnt)
		cnt -= d2[i]
	print(res - mx)
for t in range(int(input())):
	charming()


from collections import *
I = input
for _ in ' ' * int(I()):
	s = n = int(I())
	c = 0
	for (x, y) in sorted(Counter(Counter(map(int, I().split())).values()).items())[::-1]:
		c += y
		s = min(s, n - c * x)
	print(s)


from collections import Counter

def solve(ip):
	result = 0
	c = Counter(ip)
	coc = Counter(c.values())
	max_count = max(coc.keys())
	costs = [0] * (max_count + 1)
	for (k, v) in coc.items():
		for i in range(max_count + 1):
			if k >= i:
				costs[i] += (k - i) * v
			else:
				costs[i] += k * v
	return min(costs)
t = int(input())
for _ in range(t):
	n = int(input())
	ip = list(map(int, input().split()))
	res = solve(ip)
	print(res)


import sys
input = sys.stdin.readline
from collections import Counter, defaultdict

def solution(n, arr):
	c = Counter(arr)
	c_appearances = Counter([count for count in c.values()])
	l_counts = sorted(list(c_appearances.keys()))
	partial_sums = [0]
	partial_count = [0]
	sol = 10 ** 10
	remove = 0
	whole_sum = 0
	for count in l_counts:
		partial_sums.append(partial_sums[-1] + count * c_appearances[count])
		partial_count.append(partial_count[-1] + c_appearances[count])
	whole_sum = partial_sums[-1]
	for pos in range(1, len(partial_sums)):
		remove = 0
		remove += partial_sums[pos - 1]
		if pos < len(partial_sums) - 1:
			remove += whole_sum - (partial_count[-1] - partial_count[pos]) * l_counts[pos - 1] - partial_sums[pos]
		sol = min(sol, remove)
	print(sol)
T = int(input())
for t in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	solution(n, arr)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	d = []
	p = -1
	for i in sorted(R()):
		if i != p:
			d += (1,)
		else:
			d[-1] += 1
		p = i
	d.sort()
	v = [0]
	p = 0
	for i in d:
		p += i
		v += (p,)
	ans = inf
	p = -1
	n = len(v)
	for i in range(1, n):
		if d[i - 1] != p:
			ans = min(ans, v[-1] - d[i - 1] * (n - i))
		p = d[i - 1]
	print(ans)


from sys import stdin
input = stdin.readline
from heapq import heapify, heappush, heappop, heappushpop
from collections import defaultdict as dd, deque as dq, Counter as C
from math import factorial as f, ceil, gcd, sqrt, log
from bisect import bisect_left as bl, bisect_right as br
from itertools import combinations as c, permutations as p
from math import factorial as f, ceil, gcd, sqrt, log
mp = lambda : map(int, input().split())
it = lambda : int(input())
ls = lambda : list(input().strip().split())
mt = lambda r: [list(mp()) for _ in range(r)]
lcm = lambda a, b: a * b // gcd(a, b)

def fibo_n(n):
	return ((1 + sqrt(5)) / 2) ** n / sqrt(5)
mod = 1000000007
for _ in range(it()):
	a = it()
	b = list(mp())
	co = C(b)
	d = dd(lambda : 0)
	for i in co:
		d[co[i]] += 1
	out = 0
	for j in d:
		ans = 0
		for k in d:
			if k >= j:
				ans += j * d[k]
		out = max(out, ans)
	print(a - out)


import sys
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	dic = {}
	for i in a:
		if i not in dic:
			dic[i] = 0
		dic[i] += 1
	lis = []
	for i in dic:
		lis.append(dic[i])
	lis.sort()
	lis.reverse()
	Rsum = sum(lis)
	Lsum = 0
	ans = float('inf')
	for i in range(len(lis)):
		Rsum += lis[i]
		Lsum -= lis[i]
		ans = min(ans, Rsum - (i + 1) * lis[i] + Lsum)
	print(ans)


import sys
from collections import Counter
input = sys.stdin.readline
for _ in range(int(input())):
	N = int(input())
	a = list(map(int, input().split()))
	c = Counter()
	for x in a:
		c[x] += 1
	sv = sorted(c.values())
	csmn = [0] * len(sv)
	csmn[-1] = sv[-1]
	for i in range(len(sv) - 1, 0, -1):
		csmn[i - 1] = min(csmn[i], sv[i - 1])
	table = [0] * len(sv)
	l = 0
	r = 0
	for i in range(len(sv)):
		table[len(sv) - i - 1] += l
		l += sv[i]
	for i in range(len(sv)):
		r += sv[len(sv) - i - 1]
		table[i] += r - csmn[len(sv) - i - 1] * (i + 1)
	print(min(table))


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import defaultdict as dd
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdmap = lambda : map(int, stdstr().split())
stdarr = lambda : list(map(int, stdstr().split()))
mod = 1000000007
for _ in range(stdint()):
	n = stdint()
	arr = stdarr()
	c = Counter(arr)
	v = sorted(list(c.values()))
	dp = [None] * len(v)
	pref = [0]
	suff = [None] * len(v) + [0]
	for i in range(len(v)):
		pref.append(pref[-1] + v[i])
	for i in range(len(v)):
		suff[len(v) - i - 1] = suff[len(v) - i] + v[len(v) - i - 1]
	for i in range(len(v)):
		bef = pref[i]
		af = suff[i + 1] - (len(v) - i - 1) * v[i]
		dp[i] = bef + af
	print(min(dp))


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	c = Counter(a)
	for i in c:
		l.append(c[i])
	c1 = Counter(l)
	l.sort()
	m = 10000000000.0
	for i in range(len(l)):
		m = min(m, n - l[i] * (len(l) - i))
	print(m)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	counter = Counter(arr)
	counts = counter.values()
	keys = set(counts)
	result = []
	for i in keys:
		x = 0
		for j in counts:
			if j > i:
				x += j - i
			elif j < i:
				x += j
		result.append(x)
	print(min(result))


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	a = [int(token) for token in input().split()]
	counter = Counter(a)
	z = [0 for i in range(n + 10)]
	for (k, v) in counter.items():
		z[v] += 1
	prefix_sum_z = [0 for i in range(n + 10)]
	prefix_sum_z[0] = z[0]
	for i in range(1, n + 10):
		prefix_sum_z[i] += prefix_sum_z[i - 1]
		prefix_sum_z[i] += z[i] * i
	suffix_sum_z = [0 for i in range(n + 10)]
	suffix_cnt_z = [0 for i in range(n + 10)]
	for i in reversed(range(0, n + 5)):
		suffix_sum_z[i] += suffix_sum_z[i + 1]
		suffix_sum_z[i] += z[i] * i
		suffix_cnt_z[i] += suffix_cnt_z[i + 1]
		suffix_cnt_z[i] += z[i]
	ans = n
	for i in range(1, n + 1):
		local_ans = prefix_sum_z[i - 1]
		local_ans += suffix_sum_z[i + 1] - i * suffix_cnt_z[i + 1]
		ans = min(ans, local_ans)
	print(ans)


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dic = defaultdict(lambda : 0)
	for el in a:
		dic[el] += 1
	cou = list(dic.values())
	cou.sort()
	ans = float('inf')
	sumcou = sum(cou)
	nextsum = 0
	prevcou = 0
	for i in range(len(cou) - 1, -1, -1):
		sumcou -= cou[i]
		tempans = sumcou + nextsum - prevcou * cou[i]
		ans = min(ans, tempans)
		nextsum += cou[i]
		prevcou += 1
	print(ans)


import math
out = []
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	index = 0
	d = {}
	count = []
	for i in arr:
		try:
			temp = d[i]
			count[temp] += 1
		except:
			d[i] = index
			index += 1
			count.append(1)
	ans = n
	count.sort()
	check = [count[0]]
	for i in count:
		if i != check[-1]:
			check.append(i)
	for i in check:
		ctr = 0
		for j in count:
			if j > i:
				ctr += j - i
			elif j < i:
				ctr += j
		if ctr < ans:
			ans = ctr
	out.append(str(ans))
print('\n'.join(out))


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	A = [int(ele) for ele in input().split()]
	map_ = defaultdict(int)
	for n in A:
		map_[n] += 1
	min_ = min(map_.values())
	saved = 0
	values = sorted(map_.values())
	for (i, v) in enumerate(values):
		saved = max(saved, v * (len(map_) - i))
	print(sum(map_.values()) - saved)


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(s) for s in input().split(' ')]
	vals = list(Counter(arr).values())
	vals.sort(reverse=True)
	ans = 0
	for i in range(len(vals)):
		ans = max(ans, vals[i] * (i + 1))
	print(n - ans)


import sys
import collections
input = sys.stdin.readline

def println(val):
	sys.stdout.write(str(val) + '\n')

def solve(n, a):
	cnts = collections.Counter(a)
	occurences = collections.defaultdict(int)
	for key in cnts:
		occurences[cnts[key]] += 1
	ans = 0
	removed = 0
	for C in range(1, n + 10):
		ans = max(ans, C * (len(cnts) - removed))
		removed += occurences[C]
	println(n - ans)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	solve(n, a)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict

def solve(dd, c):
	ans = 0
	for item in dd.keys():
		if dd[item] >= c:
			ans += dd[item] - c
		else:
			ans += dd[item]
	return ans

def main():
	for _ in range(int(input())):
		n = int(input())
		lst = list(map(int, input().split()))
		dd = defaultdict(lambda : 0)
		r = 1
		for item in lst:
			dd[item] += 1
		ans = solve(dd, 1)
		s = set(dd.values())
		for i in s:
			ans = min(ans, solve(dd, i))
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
from collections import Counter
for _ in range(int(input())):
	n = int(input())
	w = Counter(map(int, input().split()))
	d = Counter([w[i] for i in w])
	x = sum((d[i] for i in d))
	d = sorted([(i, d[i]) for i in d])
	c = x * d[0][0]
	for i in range(1, len(d)):
		x -= d[i - 1][1]
		c = max(c, x * d[i][0])
	print(n - c)


def summator(C, lst):
	sum_ = sum(lst[:C]) + (sum(lst[C:]) - lst[C] * len(lst[C:]))
	return sum_
for t in range(int(input())):
	n = int(input())
	dic = {}
	for key in input().split():
		if key in dic:
			dic[key] += 1
		else:
			dic[key] = 1
	lst = []
	for key in sorted(dic, key=dic.get):
		lst.append(dic[key])
	ans = summator(0, lst)
	for i in set(lst):
		ans = min(ans, summator(lst.index(i), lst))
	print(ans)


import bisect
import collections
import functools
import itertools
import math
import heapq
import random
import string

def repeat(_func=None, *, times=1):

	def decorator(func):

		@functools.wraps(func)
		def wrapper(*args, **kwargs):
			for _ in range(times):
				func(*args, **kwargs)
		return wrapper
	if _func is None:
		return decorator
	else:
		return decorator(_func)

def unpack(func=int):
	return map(func, input().split())

def l_unpack(func=int):
	return list(map(func, input().split()))

def getint():
	return int(input())

def getmatrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def display_matrix(mat):
	for i in range(len(mat)):
		print(mat[i])

@repeat(times=int(input()))
def main():
	n = getint()
	arr = sorted((x for x in collections.Counter(l_unpack()).values()))
	n = len(arr)
	cumsum = [arr[0]] * n
	for i in range(1, n):
		cumsum[i] = cumsum[i - 1] + arr[i]
	ans = cumsum[-1] - arr[0] * n
	for i in range(1, n):
		temp = cumsum[-1] - arr[i] * (n - i)
		ans = min(ans, temp)
	print(ans)
MOD = 10 ** 9 + 7
main()


import sys, math, itertools, random, bisect
from collections import defaultdict
INF = sys.maxsize

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = get_array()
	store = defaultdict(int)
	for i in range(n):
		store[a[i]] += 1
	ans = []
	for key in store:
		ans.append(store[key])
	ans.sort()
	res = list(ans)
	for i in range(1, len(ans)):
		ans[i] += ans[i - 1]
	mn = INF
	length = len(ans)
	for i in range(length):
		if i == 0:
			x = 0
		else:
			x = ans[i - 1]
		y = ans[-1] - x - (length - i) * res[i]
		mn = min(mn, x + y)
	print(mn)


import math
from collections import defaultdict, Counter
from functools import lru_cache
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	count = Counter(arr)
	frequency_lis = list(count.keys())
	frequency_array = []
	for i in frequency_lis:
		frequency_array.append(count[i])
	frequency_array.sort()
	tot = 0
	le = len(frequency_array)
	for i in range(1, len(frequency_array)):
		tot += frequency_array[i] - frequency_array[0]
	ans = tot
	le -= 1
	for i in range(1, len(frequency_array)):
		diff = frequency_array[i] - frequency_array[i - 1]
		tot -= diff * le
		tot += frequency_array[i - 1]
		ans = min(ans, tot)
		le -= 1
	print(ans)


from sys import stdout
from sys import stdin

def get():
	return stdin.readline().strip()

def getf():
	return [int(i) for i in get().split()]

def put(a, end='\n'):
	stdout.write(str(a) + end)

def putf(a, sep=' ', end='\n'):
	stdout.write(sep.join([str(i) for i in a]) + end)

def fn(b, ln, x):
	res = 0
	for i in range(ln):
		if b[i] < x:
			res += b[i]
		else:
			res += b[i] - x
	return res

def solve(a, n):
	d = dict()
	for i in range(n):
		d[a[i]] = d.get(a[i], 0) + 1
	b = []
	st = set()
	ln = 0
	for i in d:
		st.add(d[i])
		b.append(d[i])
		ln += 1
	res = n
	for i in st:
		res = min(res, fn(b, ln, i))
	return res

def main():
	t = int(get())
	for i in range(t):
		n = int(get())
		a = getf()
		put(solve(a, n))
main()


import sys
import math
from sys import stdin, stdout

def sieve(N):
	primeNumbers = [True] * (N + 1)
	primeNumbers[0] = False
	primeNumbers[1] = False
	i = 2
	while i * i <= N:
		j = i
		if primeNumbers[j]:
			while j * i <= N:
				primeNumbers[j * i] = False
				j += 1
		i += 1
	return primeNumbers

def getPrime(N):
	primes = sieve(N)
	result = []
	for i in range(len(primes)):
		if primes[i]:
			result.append(i)
	return result

def factor(N):
	factors = []
	i = 1
	while i * i <= N:
		if N % i == 0:
			factors.append(i)
			if i != N // i:
				factors.append(N // i)
		i += 1
	return sorted(factors)

def gcd(a, b):
	if a < b:
		return gcd(b, a)
	if b == 0:
		return a
	return gcd(b, a % b)

def extendedGcd(a, b):
	if a < b:
		return extendedGcd(b, a)
	if b == 0:
		return [a, 1, 0]
	res = extendedGcd(b, a % b)
	x = res[2]
	y = res[1] - math.floor(a / b) * res[2]
	res[1] = x
	res[2] = y
	return res

def iterativeModularFunc(a, b, c):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % c
		a = a * a % c
		b = b // 2
	return res

def get_ints_in_variables():
	return map(int, sys.stdin.readline().strip().split())

def get_int():
	return int(input())

def get_ints_in_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def Solution(arr, n):
	hm = {}
	for v in arr:
		if v in hm:
			hm[v] += 1
		else:
			hm[v] = 1
	countArr = []
	for v in hm:
		countArr.append(hm[v])
	countArr = sorted(countArr)
	res = float('inf')
	m = len(countArr)
	for i in range(m):
		tmp = countArr[i] * (m - i)
		res = min(res, n - tmp)
	print(res)

def main():
	for _ in range(get_int()):
		n = get_int()
		arr = get_ints_in_list()
		Solution(arr, n)
main()


from math import gcd
import sys
T = int(input())
mod = 1000000007
for ia in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	h = dict()
	for i in range(n):
		if arr[i] in h:
			h[arr[i]] += 1
		else:
			h[arr[i]] = 1
	p = dict()
	for i in h:
		if h[i] in p:
			p[h[i]] += 1
		else:
			p[h[i]] = 1
	w = len(p)
	arr1 = []
	s = 0
	arr2 = sorted(p)
	for i in arr2:
		s = s + p[i]
		arr1.append(s)
	z = sys.maxsize
	for j in range(w):
		z = min(z, n - arr2[j] * (arr1[-1] - arr1[j] + p[arr2[j]]))
	print(z)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	b = Counter(map(int, input().split()))
	mi = n + 1
	for (i, v) in enumerate(sorted(b.values())):
		mi = min(mi, n - (len(b) - i) * v)
	print(mi)


import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

class DSU:

	def __init__(self, length):
		self.length = length
		self.parent = [-1] * self.length

	def getParent(self, node, start):
		if node >= self.length:
			return False
		if self.parent[node] < 0:
			if start != node:
				self.parent[start] = node
			return node
		return self.getParent(self.parent[node], start)

	def union(self, node1, node2):
		parent1 = self.getParent(node1, node1)
		parent2 = self.getParent(node2, node2)
		if parent1 == parent2:
			return False
		elif self.parent[parent1] <= self.parent[parent2]:
			self.parent[parent1] += self.parent[parent2]
			self.parent[parent2] = parent1
		else:
			self.parent[parent2] += self.parent[parent1]
			self.parent[parent1] = parent2
		return True

	def getCount(self, node):
		return -self.parent[self.getParent(node, node)]

def exact(num):
	if abs(num - round(num)) <= 10 ** (-9):
		return round(num)
	return num

def check(lst, target):
	ans = 0
	for i in lst:
		if i > target:
			ans += i - target
		else:
			ans += i
	return ans

def solve(n, lst):
	map1 = {}
	for i in lst:
		if map1.get(i) == None:
			map1[i] = 0
		map1[i] += 1
	freq = []
	for i in map1:
		freq.append(map1[i])
	freq = sorted(freq, reverse=True)
	ans = float('inf')
	summ = 0
	tot = sum(freq)
	for i in range(len(freq)):
		val = summ - i * freq[i] + (tot - (summ + freq[i]))
		ans = min(ans, val)
		summ += freq[i]
	return ans
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	print(solve(n, lst))


from collections import Counter
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	f1 = Counter(a)
	f2 = Counter(list(f1.values()))
	b = list(f2.items())
	b.sort(key=lambda x: x[0])
	ans = float('inf')
	prev = 0
	for k in b:
		ans = min(ans, n - (len(f1) - prev) * k[0])
		prev += k[1]
	print(ans)


import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def power_set(L):
	cardinality = len(L)
	n = 2 ** cardinality
	powerset = []
	for i in range(n):
		a = bin(i)[2:]
		subset = []
		for j in range(len(a)):
			if a[-j - 1] == '1':
				subset.append(L[j])
		powerset.append(subset)
	powerset_orderred = []
	for k in range(cardinality + 1):
		for w in powerset:
			if len(w) == k:
				powerset_orderred.append(w)
	return powerset_orderred

def fastPlrintNextLines(a):
	print('\n'.join(map(str, a)))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def check(mid):
	cur = 0
	for i in range(n):
		if i <= mid:
			cur += l[i][0]
			continue
		if cur >= l[i][0]:
			cur += l[i][0]
		else:
			return False
	return True
t = 1
t = int(input())
for _ in range(t):
	n = ii()
	l = li()
	d = defaultdict(lambda : 0)
	for i in l:
		d[i] += 1
	s = list(d.values())
	s.sort()
	n1 = len(s)
	ans = 10000000000000000000
	cur = 0
	for i in range(n1):
		x = s[i] * (n1 - i)
		ans = min(n - x, ans)
		cur += s[i]
	print(ans)


from collections import Counter
from bisect import bisect_right
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict(Counter(a))
	a = sorted([d[i] for i in d])
	n = len(a)
	ps = a.copy()
	for i in range(1, len(ps)):
		ps[i] += ps[i - 1]
	i = 0
	minm = ps[-1]
	while i < n:
		j = bisect_right(a, a[i])
		minm = min(minm, (0 if i == 0 else ps[i - 1]) + (ps[n - 1] - ps[j - 1]) - (n - j) * a[i])
		i = j
	print(minm)


def count(l):
	a = []
	m = 1
	for i in range(len(l) - 1):
		if l[i + 1] == l[i]:
			m += 1
		else:
			a += [m]
			m = 1
	return a + [m]
t = int(input())
for i in range(t):
	n = int(input())
	a = []
	a = [int(x) for x in input().split()]
	a = sorted(a)
	l = sorted(count(a))
	k = count(l)
	m = max(k)
	x = []
	for i in range(len(l)):
		x += [len(a) - (len(l) - i) * l[i]]
	print(min(x))


from sys import stdin
nii = lambda : map(int, stdin.readline().split())
lnii = lambda : list(map(int, stdin.readline().split()))
from collections import Counter
from bisect import bisect_left
t = int(input())
for tt in range(t):
	n = int(input())
	a = lnii()
	c = Counter(a)
	c_v = list(c.values())
	c_v.sort()
	c_s = set(c_v)
	ans = 10 ** 18
	for i in c_s:
		inx = bisect_left(c_v, i)
		t_ans = n - (len(c_v) - inx) * i
		ans = min(ans, t_ans)
	print(ans)


from collections import Counter

def solve():
	n = int(input())
	a = list(Counter(map(int, input().split())).values())
	a.sort()
	pref = [0] * (len(a) + 1)
	for i in range(1, len(pref)):
		pref[i] = pref[i - 1] + a[i - 1]
	mn = int(1e+18)
	n = len(a)
	for (i, c) in enumerate(a):
		if i > 0 and c == a[i - 1]:
			continue
		mn = min(mn, pref[i] + (pref[n] - pref[i] - c * (n - i)))
	print(mn)
t = int(input())
while t > 0:
	t -= 1
	solve()


t = int(input())
for test in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	(set1, set2) = ({}, {})
	for i in range(n):
		if a[i] not in set1:
			set1[a[i]] = 0
		set1[a[i]] += 1
	for i in set1:
		if set1[i] not in set2:
			set2[set1[i]] = 0
		set2[set1[i]] += 1
	set1 = {}
	a = sorted(set2)
	m = 0
	for i in range(len(a) - 1, -1, -1):
		set1[a[i]] = set2[a[i]]
		for j in range(i + 1, len(a)):
			set1[a[i]] += set2[a[j]]
		if a[i] * set1[a[i]] > m:
			m = a[i] * set1[a[i]]
	print(n - m)