Let's call left cyclic shift of some string $t_1 t_2 t_3 \dots t_{n - 1} t_n$ as string $t_2 t_3 \dots t_{n - 1} t_n t_1$.

Analogically, let's call right cyclic shift of string $t$ as string $t_n t_1 t_2 t_3 \dots t_{n - 1}$.

Let's say string $t$ is good if its left cyclic shift is equal to its right cyclic shift.

You are given string $s$ which consists of digits 0–9.

What is the minimum number of characters you need to erase from $s$ to make it good?


-----Input-----

The first line contains single integer $t$ ($1 \le t \le 1000$) — the number of test cases.

Next $t$ lines contains test cases — one per line. The first and only line of each test case contains string $s$ ($2 \le |s| \le 2 \cdot 10^5$). Each character $s_i$ is digit 0–9.

It's guaranteed that the total length of strings doesn't exceed $2 \cdot 10^5$.


-----Output-----

For each test case, print the minimum number of characters you need to erase from $s$ to make it good.


-----Example-----
Input
3
95831
100120013
252525252525

Output
3
5
0



-----Note-----

In the first test case, you can erase any $3$ characters, for example, the $1$-st, the $3$-rd, and the $4$-th. You'll get string 51 and it is good.

In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.

In the third test case, the given string $s$ is already good.

Source: codeforces | Difficulty: MEDIUM
Tags: Dynamic programming

Amortized analysis

Complete search

Greedy algorithms


Solutions:
import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
	s = input()[:-1]
	cnt = Counter(list(s))
	M = max(list(cnt.values()))
	if M % 2 == 0:
		ans = len(s) - (M - 1)
	else:
		ans = len(s) - M
	for a in range(10):
		for b in range(10):
			L = 0
			flag = True
			for si in s:
				if flag and int(si) == a:
					flag = False
					L += 1
				elif not flag and int(si) == b:
					flag = True
					L += 1
			ans = min(ans, len(s) - L // 2 * 2)
	print(ans)


for k in [*open(0)][1:]:
	p = [0] * 100
	for i in map(int, k[:-1]):
		for j in range(10):
			p[10 * i + j] = p[10 * j + i] + 1
	print(len(k) - 1 - max(max(p) & ~1, max(p[::11])))


t = int(input())
for _ in range(t):
	s = input()
	N = len(s)
	ans = max(0, N - 2)
	d = dict()
	d2 = dict()
	d3 = dict()
	for x in s:
		if x in d:
			d[x] += 1
		else:
			d[x] = 1
	for x in d:
		ans = min(ans, N - d[x])
	for i in range(0, 100):
		k = str(i)
		if len(k) == 1:
			k = '0' + k
		a = k[0]
		b = k[1]
		flag = False
		count = 0
		for x in s:
			if flag:
				if b == x:
					flag = False
					count += 1
				else:
					continue
			elif a == x:
				flag = True
			else:
				continue
		if N - count * 2 < ans:
			ans = N - count * 2
	print(ans)


from collections import Counter
t = int(input())
for i in range(t):
	a = list(input())
	n = len(a)
	freq = Counter(a)
	ans = n - max(freq.values())
	for i in range(10):
		for j in range(10):
			c = 0
			maxi = 0
			for k in range(n):
				if c == 0 and a[k] == str(i):
					maxi += 1
					c = 1
				elif c == 1 and a[k] == str(j):
					maxi += 1
					c = 0
			if maxi % 2 != 0:
				maxi -= 1
			ans = min(ans, n - maxi)
	print(ans)


def solution():
	a = list(map(int, list(input())))
	n = len(a)
	answer = len(a) - 2
	counter = [0] * 10
	for ai in a:
		counter[ai] += 1
	for i in range(10):
		answer = min(answer, n - counter[i])
	for i in range(10):
		if counter[i] == 0:
			continue
		for j in range(i + 1, 10):
			if counter[j] == 0:
				continue
			cur_ans = 0
			last = -1
			for k in range(n):
				if a[k] == i:
					if last == i:
						cur_ans += 1
					last = i
				elif a[k] == j:
					if last == j:
						cur_ans += 1
					last = j
				else:
					cur_ans += 1
			if (n - cur_ans) % 2 == 1:
				cur_ans += 1
			answer = min(answer, cur_ans)
	print(answer)
t = int(input())
for _ in range(t):
	solution()


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
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdarr = lambda : map(int, stdstr().split())
mod = 1000000007
for _ in range(stdint()):
	s = input()
	c = Counter(s)
	ma = -1
	for i in range(10):
		for j in range(10):
			r = 0
			for k in range(len(s)):
				if r % 2 == 0:
					if s[k] == str(i):
						r += 1
				elif s[k] == str(j):
					r += 1
			r -= r % 2
			ma = max(r, ma)
	for i in c:
		ma = max(ma, c[i])
	print(min(len(s) - ma, len(s) - 2))


def yark(a, i, j):
	z = 0
	p = str(i)
	f = p
	for k in a:
		if k == f:
			z += 1
			f = p if f != p else str(j)
	if i != j and z & 1:
		z -= 1
	return z
for t in range(int(input())):
	a = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			ans = max(ans, yark(a, i, j))
	print(len(a) - ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = list(map(int, list(input().strip())))
	ans = len(s)
	for i in range(10):
		for j in range(10):
			idx = 0
			isSwapped = False
			delete = 0
			while idx < len(s):
				match = i if isSwapped else j
				while idx < len(s) and s[idx] != match:
					delete += 1
					idx += 1
				idx += 1
				isSwapped = not isSwapped
			if (len(s) - delete) % 2 == 0:
				ans = min(ans, delete)
	for i in range(10):
		ans = min(ans, len(s) - s.count(i))
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	s = [int(ch) for ch in input().rstrip()]
	ans = 0
	for d1 in range(0, 10):
		for d2 in range(0, 10):
			if d1 == d2:
				cnt = s.count(d1)
				ans = max(ans, cnt)
				continue
			cnt = 0
			state = 0
			for item in s:
				if item == d1 and (not state):
					state = 1
					cnt += 1
				elif item == d2 and state:
					state = 0
					cnt += 1
			if state == 1:
				ans = max(ans, cnt - 1)
			else:
				ans = max(ans, cnt)
	print(len(s) - ans)


from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

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

def lm():
	return list(map(int, input().split()))
q = nn()
for _ in range(q):
	s = input()
	min_del = dict()
	min_del[-1, -1] = 0
	for i in range(0, 10):
		for j in range(0, 10):
			min_del[i, j] = 0
	for i in range(len(s) - 1):
		for j in range(10):
			min_del[j, int(s[i])] = min_del[int(s[i]), j] + 1
	m_del = max(min_del.values())
	if m_del % 2 == 0:
		print(len(s) - 1 - m_del)
	else:
		print(min(len(s) - 1 - m_del + 1, len(s) - 1 - max([min_del[i, i] for i in range(10)])))


from collections import *
import sys

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
t = ri()
for _ in range(t):
	n = input()
	l = set([x for x in n])
	cc = Counter(n)
	ans = len(n) - max(cc.values())
	val = 0
	for i in l:
		for j in l:
			if j != i:
				cnt = 0
				k = 0
				while k < len(n):
					if n[k] == i:
						z = k + 1
						while z < len(n):
							if n[z] == j:
								cnt += 1
								k = z
								break
							z += 1
					k += 1
				val = max(cnt, val)
	ans = min(ans, len(n) - 2 * val)
	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 solve(x, y, s):
	res = 0
	for c in s:
		if ord(c) - ord('0') == x:
			res += 1
			(x, y) = (y, x)
	if x != y and res % 2:
		res -= 1
	return res

def main():
	try:
		for _ in range(inp()):
			s = input()
			n = len(s)
			ans = 0
			for x in range(10):
				for y in range(10):
					ans = max(ans, solve(x, y, s))
			print(n - 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()


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	a = [int(i) for i in input()]
	n = len(a)
	ans = 0
	p = [0, 0]
	for i in range(0, 10):
		for j in range(0, 10):
			cnt = 0
			cur = [i, j]
			ind = 0
			for k in a:
				if k == cur[ind]:
					cnt += 1
					ind ^= 1
			if i != j:
				cnt -= cnt & 1
			ans = max(ans, cnt)
	print(n - ans)


case = int(input())
for _ in range(case):
	n = input()
	ln = len(n)
	ans = 1000000
	for i in range(10):
		tmp = n.count(str(i))
		tmp = ln - tmp
		if tmp < ans:
			ans = tmp
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			switch = 0
			tmp = 0
			for k in range(ln):
				if switch == 0:
					if n[k] == str(i):
						switch = 1
				if switch == 1:
					if n[k] == str(j):
						switch = 0
						tmp += 2
			tmp = ln - tmp
			if tmp < ans:
				ans = tmp
	print(ans)


t = int(input().split()[0])
for case in range(t):
	s = input().split()[0]
	best = len(s)
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			curr = 0
			foundFirst = True
			if s.count(str(i)) == 0:
				continue
			l = s.index(str(i))
			r = l + 1
			while l < len(s):
				while r < len(s):
					if foundFirst == False and s[r] == str(i):
						foundFirst = True
					if foundFirst == True and s[r] == str(j):
						curr += 2
						foundFirst = False
						break
					r += 1
				l = r
				r += 1
			if len(s) - curr < best:
				best = len(s) - curr
	for i in range(10):
		if len(s) - s.count(str(i)) < best:
			best = len(s) - s.count(str(i))
	print(best)


def solve(a, b, s):
	res = 0
	si = 1
	for i in range(0, len(s)):
		if ord(s[i]) - ord('0') == a and si == 1:
			res += 1
			si = -si
		elif ord(s[i]) - ord('0') == b and si == -1:
			res += 1
			si = -si
	if res & 1 and res > 1 and (a != b):
		res -= 1
	return res
tc = int(input())
while tc:
	s = input()
	max1 = 0
	for i in range(0, 10):
		for j in range(0, 10):
			max1 = max(max1, solve(i, j, s))
	print(len(s) - max1)
	tc -= 1


import sys
from collections import Counter

def best(case):
	if len(case) == 0 or len(case) == 2:
		return 0
	best = max(Counter(case).items(), key=lambda x: x[1])[1]
	for i in range(10):
		for j in range(10):
			looking_for = i
			first = True
			length = 0
			for c in case:
				if int(c) == looking_for and first:
					first = False
					looking_for = j
				elif int(c) == looking_for and (not first):
					first = True
					looking_for = i
					length += 2
			if length > best:
				best = length
	return len(case) - best

def main(cases):
	for case in cases:
		print(best(case))
cases = []
count = 1
for (e, line) in enumerate(sys.stdin.readlines()):
	if e == 0:
		continue
	cases.append(line.strip())
main(cases)


for _ in range(int(input())):
	s = input()
	n = len(s)
	cnt = [0] * 10
	ind = [[] for i in range(10)]
	for i in range(n):
		cnt[int(s[i])] += 1
		ind[int(s[i])] += [i]
	ans = n - max(cnt)
	for i in range(10):
		for j in range(i + 1, 10):
			l = 0
			r = 0
			cur = []
			a = 0
			fl = -1
			for k in range(cnt[i] + cnt[j]):
				if l == cnt[i]:
					cur.append(ind[j][r])
					r += 1
					if fl == 0:
						a += 1
					fl = 1
				elif r == cnt[j]:
					cur.append(ind[i][l])
					if fl == 1:
						a += 1
					fl = 0
					l += 1
				elif ind[i][l] < ind[j][r]:
					cur.append(ind[i][l])
					l += 1
					if fl == 1:
						a += 1
					fl = 0
				else:
					cur.append(ind[j][r])
					r += 1
					if fl == 0:
						a += 1
					fl = 1
			a += 1
			ans = min(ans, n - a + a % 2)
	print(ans)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	maxx = 0
	maxxs = 0
	for i in range(0, 10):
		maxxs = max(maxxs, s.count(str(i)))
	for i in range(0, 100):
		cnt = 0
		y = str(i)
		if len(y) == 1:
			y = '0' + y
		f = 0
		for j in range(n):
			if s[j] == y[0]:
				f = 1
			elif s[j] == y[1] and f == 1:
				cnt += 1
				f = 0
		maxx = max(maxx, cnt)
	print(min(len(s) - 2 * maxx, len(s) - maxxs))


def fun(x):
	return x[0]
import sys
from collections import defaultdict
t = int(input())
for i in range(t):
	n = list(input())
	lenn = len(n)
	d = defaultdict(int)
	for j in n:
		d[j] += 1
	freq = []
	for j in range(10):
		freq.append([d[str(j)], j])
	freq.sort(key=fun, reverse=True)
	maxl = 2
	maxl = max(maxl, freq[0][0])
	for j in range(10):
		for k in range(j + 1, 10):
			if freq[j][0] + freq[k][0] <= maxl:
				break
			ll = 0
			xx = str(freq[j][1])
			yy = str(freq[k][1])
			ii = 0
			c = 0
			while ii < lenn:
				f1 = 0
				f2 = 0
				while ii < lenn and (not n[ii] == yy):
					ii += 1
				if ii == lenn:
					break
				if n[ii] == yy:
					f1 = 1
				while ii < lenn and (not n[ii] == xx):
					ii += 1
				if ii == lenn:
					break
				if n[ii] == xx:
					f2 = 1
				if f1 and f2:
					c += 2
			ll = c
			c = 0
			ii = 0
			c = 0
			while ii < lenn:
				f1 = 0
				f2 = 0
				while ii < lenn and (not n[ii] == xx):
					ii += 1
				if ii == lenn:
					break
				if n[ii] == xx:
					f1 = 1
				while ii < lenn and (not n[ii] == yy):
					ii += 1
				if ii == lenn:
					break
				if n[ii] == yy:
					f2 = 1
				if f1 and f2:
					c += 2
			ll = max(ll, c)
			maxl = max(maxl, ll)
	print(lenn - maxl)


pairs = tuple(((i, j) for i in range(10) for j in range(10) if i != j))
for _ in range(int(input())):
	s = tuple((int(i) for i in input()))
	ans = []
	for digit in range(10):
		counter = s.count(digit)
		while ans and len(s) - counter < ans[-1]:
			ans.pop()
		ans.append(len(s) - counter)
	for pair in pairs:
		flag = 0
		counter = 0
		for digit in s:
			if pair[0] == digit and flag == 0:
				flag = 1
			elif pair[1] == digit and flag == 1:
				flag = 0
				counter += 2
		while ans and len(s) - counter < ans[-1]:
			ans.pop()
		ans.append(len(s) - counter)
	print(ans[0])


from os import path
import sys, time
mod = int(1000000000.0 + 7)
from math import ceil, floor, gcd, log, log2, factorial, sqrt
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, permutations
from bisect import *
from functools import reduce
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
localsys = 0
start_time = time.time()
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)

def ceill(n, x):
	return (n + x - 1) // x
T = 1

def solve():
	s = S()
	(n, cnt) = (len(s), [0] * 10)
	for i in s:
		cnt[int(i)] += 1
	(st, ans) = (set(s), n - max(cnt))
	for i in st:
		for j in st:
			if i == j:
				continue
			sr = ''.join([kl for kl in s if kl == i or kl == j])
			ans = min(ans, n - 2 * sr.count(i + j))
	print(ans)

def run():
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
run()
T = I() if T else 1
for _ in range(T):
	solve()
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


for s in [*open(0)][1:]:
	a = [0] * 10
	b = [0] * 100
	i = 0
	for j in map(int, s[:-1]):
		for k in range(10):
			b[10 * j + k] += k == j or (a[k] > a[j]) * 2
		i += 1
		a[j] = i
	print(i - max(b))


def solver(a, b):
	result = 0
	for elem in s:
		if elem == a:
			result += 1
			(a, b) = (b, a)
	if result % 2 != 0 and a != b:
		result -= 1
	return result
for _ in range(int(input())):
	s = input()
	(m, answer) = (0, 0)
	for i in range(10):
		for j in range(10):
			answer = max(answer, solver(str(i), str(j)))
	print(len(s) - answer)


t = int(input())
for _ in range(t):
	s = list(map(int, input().strip()))
	n = len(s)
	rm = n - max([s.count(i) for i in range(10)])
	for i in range(10):
		for j in range(10):
			sw = 1
			add = 0
			for k in range(n):
				if sw:
					if s[k] == i:
						add += 1
						sw ^= 1
				elif s[k] == j:
					add += 1
					sw ^= 1
			add -= add % 2
			rm = min(rm, n - add)
	print(rm)


def main():
	from collections import Counter, defaultdict
	from sys import stdin
	input = stdin.readline
	for _ in range(int(input())):
		s = input().strip()
		n = len(s)
		arr = Counter(s)
		m = 0
		for i in range(10):
			for j in range(10):
				c = str(i)
				d = str(j)
				if c == d:
					m = max(m, arr[c])
					continue
				f = c
				ans = 0
				for k in s:
					if k == f:
						ans += 1
						if f == c:
							f = d
						else:
							f = c
				l = ans // 2 * 2
				m = max(m, l)
		print(n - m)
main()


for i in ' ' * int(input()):
	s = input()
	countL = [0] * 10
	for i in s:
		countL[int(i)] += 1
	mx = max(countL)
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			frontcount = 0
			count = 0
			for k in s:
				if int(k) == i and frontcount == count:
					frontcount += 1
				if int(k) == j and frontcount == count + 1:
					count += 1
			if mx < count * 2:
				mx = count * 2
	print(len(s) - mx)


t = int(input())
for i in range(t):
	s = str(input())
	n = len(s)
	matrix = [[0] * 10 for j in range(10)]
	for j in range(10):
		for k in range(10):
			if j != k:
				str1 = str(j) + str(k)
				a = 0
				x = 0
				for l in range(n):
					if a % 2 == 0:
						if s[l] == str1[0]:
							x += 1
							a += 1
					elif s[l] == str1[1]:
						x += 1
						a += 1
				if x % 2 == 1:
					x -= 1
				matrix[j][k] = x
	lis = [0] * 10
	for j in range(n):
		lis[int(s[j])] += 1
	ans = n - max(lis)
	for j in range(10):
		temp = max(matrix[j])
		ans = min(ans, n - temp)
	print(ans)


for s in [*open(0)][1:]:
	a = [0] * 100
	for i in map(int, s[:-1]):
		for j in range(10):
			a[10 * i + j] = a[10 * j + i] + 1
	print(len(s) - 1 - max(max(a) & ~1, *a[::11]))


from collections import defaultdict as dd
t = int(input())
for _ in range(t):
	s = input()
	mct = 0
	for i in range(10):
		for j in range(10):
			ct = 0
			flag = 1
			for k in range(len(s)):
				if flag:
					if int(s[k]) == i:
						ct += 1
						flag ^= 1
				elif int(s[k]) == j:
					ct += 1
					flag ^= 1
			if i == j:
				mct = max(mct, ct)
			else:
				mct = max(mct, ct - ct % 2)
	print(len(s) - mct)


def get(s, a, b):
	c = 0
	for i in s:
		if i == a:
			(a, b) = (b, a)
			c += 1
	if c % 2 != 0:
		c -= 1
	return c
for _ in range(int(input())):
	s = input()
	n = len(s)
	maxi = 0
	for i in range(10):
		for j in range(10):
			if i == j:
				x = s.count(str(i))
			else:
				x = get(s, str(i), str(j))
			maxi = max(maxi, x)
	print(n - maxi)


import math
import sys
import bisect
t = int(input())
for _ in range(t):
	s = input()
	d = {}
	for i in range(10):
		d[i] = []
	for i in range(len(s)):
		d[int(s[i])].append(i)
	maxi = 0
	for i in range(10):
		maxi = max(maxi, len(d[i]))
	for i in range(10):
		for j in range(10):
			if i != j and len(d[i]) > 0 and (len(d[j]) > 0):
				cnt = 0
				i1 = -1
				while 1:
					i1 = bisect.bisect(d[i], i1)
					if i1 >= len(d[i]):
						break
					i1 = d[i][i1]
					i1 = bisect.bisect(d[j], i1)
					if i1 >= len(d[j]):
						break
					i1 = d[j][i1]
					cnt += 2
				maxi = max(maxi, cnt)
	print(len(s) - maxi)


from __future__ import division, print_function
import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io
if sys.version_info[0] < 3:
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip
MOD = 998244353
mod = 10 ** 9 + 7

def prepare_factorial(mod=mod):
	fact = [1]
	for i in range(1, 200005):
		fact.append(fact[-1] * i % mod)
	ifact = [0] * 200005
	ifact[200004] = pow(fact[200004], mod - 2, mod)
	for i in range(200004, 0, -1):
		ifact[i - 1] = i * ifact[i] % mod
	return (fact, ifact)

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r, fact, ifact):
	t = fact[n] * (ifact[r] * ifact[n - r]) % MOD % MOD
	return t

def get_n(Sum):
	ans = (-1 + sqrt(1 + 8 * Sum)) // 2
	return ans

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def lrfind(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def check_sorted(a):
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			return False
	return True

def ceil(n, k=1):
	return n // k + (n % k != 0)

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

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

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

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

def lw():
	return input().split()

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

def prr(a, sep=' ', end='\n'):
	print(sep.join(map(str, a)), end=end)

def dd():
	return defaultdict(int)

def ddl():
	return defaultdict(list)

def write(s):
	return sys.stdout.write(s)

def main():
	t = ii()
	for _ in range(t):
		s = input()
		n = len(s)
		chars = set(s)
		ma = 0
		for i in chars:
			ma = max(ma, s.count(i))
		for i in chars:
			for j in chars:
				if i == j:
					continue
				odd = True
				ans = 0
				for k in s:
					if odd and k == i:
						odd = not odd
						ans += 1
					if not odd and k == j:
						odd = not odd
						ans += 1
				if ans & 1:
					ma = max(ans - 1, ma)
				else:
					ma = max(ans, ma)
		print(n - ma)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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 i in range(int(input())):
	a = input()
	n = len(a)
	d = n
	for j in range(10):
		e = [0] * (9 - j)
		c = 0
		g = 0
		h = [0] * (9 - j)
		for k in range(n):
			y = int(a[k])
			if y == j:
				if c > 0:
					for l in range(9 - j):
						e[l] += f[l]
				f = [0] * (9 - j)
				c += 1
			elif c > 0 and y > j:
				z = y - j - 1
				if f[z] == 0:
					f[z] = 1
			elif c == 0 and y > j:
				z = y - j - 1
				if h[z] == 0:
					h[z] = 1
		if c > 0:
			for l in range(9 - j):
				e[l] += f[l]
		c0 = c
		for k in range(9 - j):
			if h[k] == 1 and c0 > 0 and (f[k] == 0):
				e[k] += 1
			c = max(c, 2 * e[k])
		d = min(d, n - c)
	print(d)


def everythingfine(s, n):
	for i in range(n):
		if s[i] != s[(i + 2) % n]:
			return False
	return True
for _ in range(int(input())):
	s = input()
	n = len(s)
	maxi = 0
	temp = list('0123456789')
	d = dict()
	for i in temp:
		d[i] = s.count(i)
		maxi = max(maxi, d[i])
	if everythingfine(s, n):
		print('0')
		continue
	ans = min(n - 2, n - maxi)
	for i in range(10):
		for j in range(10):
			if i == j or d[temp[i]] == 0 or d[temp[j]] == 0:
				continue
			tempans = 0
			diff = 0
			for x in s:
				if x == temp[i] and diff == 1:
					tempans += 1
				elif x == temp[j] and diff == 0:
					tempans += 1
				elif x == temp[i] and diff == 0:
					diff += 1
				elif x == temp[j] and diff == 1:
					diff -= 1
				else:
					tempans += 1
			if diff == 0:
				ans = min(ans, tempans)
	print(ans)


from collections import Counter

def main():
	return '\n'.join(map(str, (nCharactersToEraseFrom(input()) for _ in range(int(input())))))

def nCharactersToEraseFrom(string):
	repetition = Counter(string)
	longestLength1 = repetition.most_common(1)[0][1]
	halfLength = longestLength1 // 2
	letters = tuple(set(string))
	if len(letters) > 1:
		longestLength2 = longestLength1
		for i in range(len(letters) - 1):
			if repetition[letters[i]] > halfLength:
				for j in range(i + 1, len(letters)):
					if repetition[letters[j]] > halfLength:
						l = goodStringLengthFrom(string, {letters[i], letters[j]})
						if l > longestLength2:
							longestLength2 = l
		if longestLength2 != longestLength1:
			return len(string) - (longestLength2 - 1 if longestLength2 % 2 else longestLength2)
	return len(string) - longestLength1

def goodStringLengthFrom(string, pairOfLetters):
	currLetter = [0]
	return sum((1 for l in string if isElement(l, pairOfLetters, currLetter)))

def isElement(letter, letters, currLetter):
	if letter in letters and letter != currLetter[0]:
		currLetter[0] = letter
		return True
print(main())


for _ in range(int(input())):
	arr = list(map(int, input()))
	ans = int(10000000000.0)
	l = len(arr)
	for i in range(10):
		for j in range(10):
			now = i
			cnt = 0
			for k in range(l):
				if arr[k] == now:
					if now == i:
						now = j
					else:
						now = i
				else:
					cnt += 1
			if now == i:
				ans = min(cnt, ans)
	print(ans)


from sys import stdin
tt = int(stdin.readline())
nn = '0123456789'
for loop in range(tt):
	s = stdin.readline()
	s = s[:-1]
	ans = len(s)
	for fi in nn:
		for sc in nn:
			state = 0
			now = 0
			for i in s:
				if i == fi and state == 0:
					now += 1
					state = 1
				elif i == sc and state == 1:
					now += 1
					state = 0
			if fi == sc:
				ans = min(ans, len(s) - now)
			else:
				ans = min(ans, len(s) - now // 2 * 2)
	print(ans)


for t in range(int(input())):
	s = input()
	n = len(s)
	index = [[] for i in range(10)]
	for i in range(len(s)):
		index[int(s[i])].append(i)
	ans = float('inf')
	for i in range(10):
		for j in range(10):
			if i == j:
				ans = min(ans, n - len(index[i]))
			else:
				i1 = j1 = 0
				cnt = 0
				last = -1
				while True:
					if cnt % 2 == 0:
						if i1 == len(index[i]):
							break
						if index[i][i1] > last:
							last = index[i][i1]
							cnt += 1
						i1 += 1
					else:
						if j1 == len(index[j]):
							break
						if index[j][j1] > last:
							last = index[j][j1]
							cnt += 1
						j1 += 1
				if cnt % 2:
					cnt -= 1
				ans = min(ans, n - cnt)
	print(ans)


import sys, math, cmath, time
start_time = time.time()

def solve():
	s = insr()
	q = max(counter(s))
	for i in range(10):
		for j in range(10):
			l = 0
			c = 0
			for k in range(len(s)):
				if s[k] == str(i) or s[k] == str(j):
					if l % 2 == 0 and s[k] == str(i):
						l = l + 1
					elif l % 2 != 0 and s[k] == str(j):
						c = c + 1
						l = l + 1
			q = max(q, c * 2)
	print(len(s) - q)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

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

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

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

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

def counter(a):
	q = [0] * 10
	for i in range(len(a)):
		q[int(a[i])] = q[int(a[i])] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt, floor, factorial, gcd, log, ceil
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
import itertools

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

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

def Lstr():
	return list(sys.stdin.readline().strip())

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

def Mstr():
	return map(str, sys.stdin.readline().strip().split())

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

def Hash():
	return dict()

def Mod():
	return 1000000007

def Ncr(n, r, p):
	return fact[n] * (ifact[r] * ifact[n - r] % p) % p

def Most_frequent(list):
	return max(set(list), key=list.count)

def Mat2x2(n):
	return [List() for _ in range(n)]

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

def solution():
	for i in range(Int()):
		a = Lstr()
		ans = 0
		for i in range(10):
			for j in range(10):
				count = 0
				x = 0
				for k in a:
					if x == 0 and k == str(i):
						x = 1
						count += 1
					elif x == 1 and k == str(j):
						x = 0
						count += 1
				if count % 2 == 0 or i == j:
					ans = max(ans, count)
		print(len(a) - ans)
solution()


from collections import Counter

def check(a, b):
	t = 0
	af = 0
	for i in s:
		if i == a:
			if af == 0:
				af = 1
		elif i == b:
			if af == 1:
				t += 2
				af = 0
	return t
for i in range(int(input())):
	s = [int(i) for i in input()]
	cnt = Counter(s)
	ans = 0
	for a in range(0, 10):
		for b in range(0, 10):
			ans = max(ans, check(a, b))
	print(min(len(s) - ans, len(s) - max(cnt.values())))


from collections import Counter
t = int(input())
for _ in range(t):
	numList = [int(x) for x in list(input())]
	l = len(numList)
	singleCharCase = l - max(Counter(numList).values())
	doubleCharCase = l
	for i in range(9):
		for j in range(i + 1, 10):
			A = i
			B = j
			cnts = 0
			prev = -1
			for x in numList:
				if x == A and prev != A:
					cnts += 1
					prev = A
				elif x == B and prev != B:
					cnts += 1
					prev = B
			cnts = cnts // 2 * 2
			doubleCharCase = min(doubleCharCase, l - cnts)
	print(min(singleCharCase, doubleCharCase))


possibles = []
for i in range(10):
	for j in range(10):
		possibles.append(str(i) + str(j))
for _ in range(int(input())):
	s = input()
	max = 2
	for st in possibles:
		length = 0
		j = 0
		for digit in s:
			if digit == st[j]:
				length += 1
				if j == 0:
					j += 1
					if st[0] == st[1] and length > max:
						max = length
				else:
					j -= 1
					if length > max:
						max = length
	print(len(s) - max)


for _ in range(int(input())):
	s = input()
	l = len(s)
	real_ans = l
	for i in range(10):
		for j in range(10):
			flag = True
			ans = l
			for t in range(l):
				if flag:
					if s[t] == str(i):
						ans -= 1
						flag = False
				elif s[t] == str(j):
					ans -= 1
					flag = True
			if not flag and i != j:
				ans += 1
			real_ans = min(real_ans, ans)
	print(real_ans)


def count_alternation(s, a, b):
	n = len(s)
	for i in range(n):
		if s[i] == a:
			break
		if s[i] == b:
			(a, b) = (b, a)
			break
	i1 = 0
	for i in range(n)[::-1]:
		if s[i] == b:
			i1 = i
			break
	flip = {a: b, b: a}
	which = a
	count = 0
	for i in range(i1 + 1):
		if s[i] == which:
			if which == b:
				count += 1
			which = flip[which]
	return 2 * count

def solve(s):
	s = [ord(c) - ord('0') for c in s]
	k = 10
	n = len(s)
	counts = [0] * k
	for i in range(n):
		counts[s[i]] += 1
	result = max(counts)
	for a in range(k):
		for b in range(a + 1, k):
			if counts[a] == 0 or counts[b] == 0:
				continue
			result = max(result, count_alternation(s, a, b))
	return n - result

def main(istr, ostr):
	t = int(istr.readline())
	for _ in range(t):
		s = istr.readline().strip()
		result = solve(s)
		print(result, file=ostr)
import sys
main(sys.stdin, sys.stdout)


import sys
import bisect as bi
import math
from collections import defaultdict as dd
import heapq
input = sys.stdin.readline
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def msb(n):
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	n |= n >> 32
	n |= n >> 64
	return n - (n >> 1)

def pref(a, n, f):
	pre = [0] * n
	if f == 0:
		pre[0] = a[0]
		for i in range(1, n):
			pre[i] = a[i] + pre[i - 1]
	else:
		pre[-1] = a[-1]
		for i in range(n - 2, -1, -1):
			pre[i] = pre[i + 1] + a[i]
	return pre
for _ in range(inin()):
	s = sin().strip()
	d = dd(list)
	d1 = dd(int)
	n = len(s)
	for i in range(n):
		d[s[i]] += [i]
		d1[s[i]] += 1
	ans = max(d1.values())
	l = list(d.keys())
	for i in l:
		for j in l:
			if i != j:
				l1 = d[i] + d[j]
				l1.sort()
				curr = i
				te = 1
				p = l1.index(d[i][0])
				for k in l1[p + 1:]:
					if s[k] == curr:
						continue
					else:
						te += 1
						if curr == i:
							curr = j
						else:
							curr = i
				if te % 2 == 1:
					te -= 1
				ans = max(ans, te)
				l1 = []
	print(n - ans)


from sys import stdin
t = int(stdin.readline().strip())
for _ in range(t):
	S = stdin.readline().strip()
	mindelete = len(S)
	for i in range(10):
		for j in range(10):
			ichar = str(i)
			jchar = str(j)
			first = True
			delete = len(S)
			for c in S:
				if c == ichar and first:
					first = False
				elif c == jchar and (not first):
					first = True
					delete -= 2
			mindelete = min(mindelete, delete)
	for i in range(10):
		ichar = str(i)
		delete = 0
		for c in S:
			if c != ichar:
				delete += 1
		mindelete = min(mindelete, delete)
	print(mindelete)


from collections import Counter

def get(s, a, b):
	c = 0
	for i in s:
		if i == a:
			(a, b) = (b, a)
			c += 1
	if c % 2 != 0:
		c -= 1
	return c
for _ in range(int(input())):
	s = list(input())
	l = len(s)
	maxx = -1
	for i in range(10):
		for j in range(10):
			if i == j:
				x = s.count(str(i))
			else:
				x = get(s, str(i), str(j))
			maxx = max(maxx, x)
	print(l - maxx)


from collections import Counter
for _ in range(int(input())):
	l = str(input())
	c = 0
	k = 0
	ans = 0
	str1 = str(c) + str(k)
	d = Counter(l)
	for i in range(1, 101):
		count = 0
		cr = 0
		if str1[0] != str1[1]:
			for j in range(len(l)):
				if l[j] == str1[0] or cr == 1:
					if l[j] == str1[1]:
						count += 2
						cr = 0
					else:
						cr = 1
		if i % 10 == 0:
			k = 0
			c += 1
			str1 = str(c) + str(k)
		else:
			k += 1
			str1 = str(c) + str(k)
		ans = max(ans, count)
	print(min(len(l) - ans, len(l) - max(d.values())))


def mergeSort(L, R, a):
	i = j = k = 0
	while i < len(L) and j < len(R):
		if L[i] < R[j]:
			a[k] = 0
			i += 1
		else:
			a[k] = 1
			j += 1
		k += 1
	while i < len(L):
		a[k] = 0
		i += 1
		k += 1
	while j < len(R):
		a[k] = 1
		j += 1
		k += 1
for _ in range(int(input())):
	s = input()
	arr = [0] * 10
	for i in range(len(s)):
		if arr[int(s[i])] == 0:
			arr[int(s[i])] = [i]
		else:
			arr[int(s[i])].append(i)
	possible = 2
	for i in range(10):
		if arr[i] != 0:
			possible = max(possible, len(arr[i]))
		for j in range(i + 1, 10):
			if arr[i] != 0 and arr[j] != 0:
				a = [0] * (len(arr[i]) + len(arr[j]))
				mergeSort(arr[i], arr[j], a)
				pair = 0
				k = 0
				while k < len(a):
					start = a[k]
					while k < len(a) and a[k] == start:
						k += 1
					if k == len(a):
						break
					start = a[k]
					while k < len(a) and a[k] == start:
						k += 1
					pair += 1
				possible = max(possible, 2 * pair)
	print(len(s) - possible)


for i in range(int(input())):
	s = input()
	count = [[0 for i in range(10)] for i in range(10)]
	for i in s:
		d = int(i)
		for p in range(10):
			count[d][p] = count[p][d] + 1
	print(len(s) - max(max([max(i) for i in count]) // 2 * 2, max([count[i][i] for i in range(10)])))


t = int(input())
for _ in range(t):
	s = input()
	mct = 0
	for i in range(10):
		for j in range(10):
			ct = 0
			flag = 1
			for k in range(len(s)):
				if flag:
					if int(s[k]) == i:
						ct += 1
						flag ^= 1
				elif int(s[k]) == j:
					ct += 1
					flag ^= 1
			if i == j:
				mct = max(mct, ct)
			else:
				mct = max(mct, ct - ct % 2)
	print(len(s) - mct)


t = int(input())
for i in range(t):
	s = input()
	v = len(s)
	ansf = 0
	bq = [0] * 10
	l = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	for j in range(len(s)):
		bq[int(s[j])] += 1
	ansf = max(bq)
	for j in range(10):
		for k in range(10):
			if j != k:
				ans = 0
				w = 0
				while w < v:
					p = 0
					q = 0
					while w < v and s[w] != l[j]:
						w += 1
						p = 1
					if p == 1:
						w += 1
						while w < v and s[w] != l[k]:
							w += 1
							q = 1
						if q == 1 and w < v:
							ans += 2
							w += 1
						else:
							if w < v:
								ans += 2
							w += 1
					elif w < v:
						w += 1
						while w < v and s[w] != l[k]:
							w += 1
							q = 1
						if q == 1 and w < v:
							ans += 2
							w += 1
						else:
							if w < v:
								ans += 2
							w += 1
				ansf = max(ans, ansf)
	print(v - ansf)


from collections import Counter
d = [str(i) + str(j) for i in range(10) for j in range(10)]
cases = int(input())
for t in range(cases):
	n = input()
	cc = Counter(n)
	mv = max(cc.values())
	for i in d:
		s = 0
		(a, b) = (i[0], i[1])
		f1 = n.find(a)
		f2 = n.find(b, f1 + 1)
		while True:
			s += 2
			f1 = n.find(a, f2 + 1)
			f2 = n.find(b, f1 + 1)
			if f1 == -1 or f2 == -1:
				break
		mv = max(mv, s)
	print(len(n) - mv)


import sys

def make_pat(p):
	bit = 0
	size = 0
	for i in range(len(arr)):
		if bit == 0 and arr[i] == p[0]:
			bit = 1
			size += 1
		elif bit == 1 and arr[i] == p[1]:
			bit = 0
			size += 1
	if p[0] == p[1]:
		return size
	elif size % 2 == 0:
		return size
	else:
		return 0
tc = int(sys.stdin.readline())
for _ in range(tc):
	arr = list(sys.stdin.readline().rstrip())
	ans = 0
	for i in range(10):
		for j in range(10):
			temp = make_pat(str(i) + str(j))
			ans = max(ans, temp)
	print(len(arr) - ans)


for t in [*open(0)][1:]:
	g = [0] * 100
	for i in map(int, t[:-1]):
		for j in range(10):
			g[10 * i + j] = g[10 * j + i] + 1
	print(len(t) - 1 - max(max(g) & ~1, max(g[::11])))


for s in [*open(0)][1:]:
	a = [0] * 10
	b = [0] * 10
	c = [0] * 100
	i = 0
	for x in map(int, s[:-1]):
		for j in range(10):
			c[10 * j + x] += (a[j] > a[x]) * 2
		i += 1
		a[x] = i
		b[x] += 1
	print(i - max(b + c))


for g in range(int(input())):
	s = input()
	slov = [0] * 10
	data = [0] * 10
	for i in range(len(s)):
		data[int(s[i])] += 1
	ans = max(data)
	for i in range(10):
		slov[i] = 1
	for i in range(len(s)):
		if slov[int(s[i])] == 1:
			slov[int(s[i])] = 0
			data = [0] * 10
			data[int(s[i])] = 1
			data1 = [1] * 10
			for j in range(i, len(s)):
				if s[j] != s[i] and data1[int(s[j])] == 1:
					data1[int(s[j])] = 0
					data[int(s[j])] += 1
				elif s[j] == s[i]:
					data[int(s[i])] += 1
					data1 = [1] * 10
			r = max(data)
			data.remove(r)
			ans = max(ans, 2 * max(data))
	print(len(s) - ans)


for _ in range(int(input())):
	ch = str(input())
	ans = 0
	for i in range(0, 10):
		ct = 0
		for c in ch:
			if int(c) == i:
				ct = ct + 1
		ans = max(ans, ct)
		for j in range(0, 10):
			ct = 0
			for c in ch:
				if ct % 2 == 0:
					if int(c) == i:
						ct = ct + 1
				elif int(c) == j:
					ct = ct + 1
			if ct % 2:
				ct = ct - 1
			ans = max(ans, ct)
	print(len(ch) - ans)


import sys
from string import digits

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	S = input()
	N = len(S)
	ans = INF
	for a in digits:
		for b in digits:
			is_a = True
			cnt = 0
			for i in range(N):
				if is_a and S[i] == a:
					is_a = False
					cnt += 1
				elif not is_a and S[i] == b:
					is_a = True
					cnt += 1
			if a != b:
				cnt -= cnt & 1
			ans = min(ans, N - cnt)
	print(ans)


for i in range(int(input())):
	a = list(map(int, input()))
	z = len(a) + 1
	a1 = [0] * 10
	a2 = [z] * 10
	a3 = list(range(10))
	for (j, x) in enumerate(a):
		a1[x] += 1
		if a2[x] == z:
			a2[x] = j
	a4 = [x[0] for x in sorted(zip(a3, a2), key=lambda q: q[1])]
	b = [[0 for y in range(10)] for x in range(10)]
	for j in range(10):
		for k in range(j + 1, 10):
			j1 = a4[j]
			k1 = a4[k]
			v = True
			c = 0
			for x in a:
				if v and x == j1:
					v = False
					c += 1
				elif not v and x == k1:
					v = True
					c += 1
			b[j1][k1] = c
	b1 = max(map(max, b))
	b1 -= b1 % 2
	print(len(a) - max(max(a1), b1))


T = int(input())

def f(x, y, a):
	correct = 0
	for c in a:
		if c == x:
			correct += 1
			(x, y) = (y, x)
	if x != y and correct % 2 == 1:
		correct -= 1
	return correct
while T:
	s = input()
	array = [int(x) for x in s]
	ans = 0
	for x in range(10):
		for y in range(10):
			ans = max(ans, f(x, y, array))
	print(len(s) - ans)
	T = T - 1


import re
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	if n == 2:
		print(0)
		continue
	maxcount = 0
	for i in range(10):
		a = ''
		a += str(i)
		count = s.count(a)
		if count > maxcount:
			maxcount = count
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			count = 0
			curr = str(i)
			for k in range(n):
				if s[k] == curr:
					count += 1
					if curr == str(i):
						curr = str(j)
					else:
						curr = str(i)
			if i != j:
				if count % 2 != 0:
					count -= 1
			if count > maxcount:
				maxcount = count
	print(n - maxcount)


def minErase(s):
	n = len(s)
	maxCnt = 0
	for i in range(10):
		for j in range(10):
			currChar = i
			cnt = 0
			for c in s:
				if int(c) == currChar:
					cnt += 1
					currChar = j if currChar == i else i
			maxCnt = max(maxCnt, cnt - 1 if i != j and cnt % 2 != 0 else cnt)
	ans = n - maxCnt
	print(ans)
t = int(input())
for _ in range(t):
	s = input()
	minErase(s)


def solve(s, x, y):
	res = 0
	for c in s:
		if int(c) - 0 == x:
			res += 1
			(x, y) = (y, x)
	if x != y and res % 2 == 1:
		res -= 1
	return res
t = int(input())
for _ in range(t):
	s = input()
	ans = 0
	for x in range(10):
		for y in range(10):
			ans = max(ans, solve(s, x, y))
	print(len(s) - ans)


import sys

def rs():
	return sys.stdin.readline().rstrip()

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

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

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

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

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')
from collections import Counter

def solve(s):
	n = len(s)
	best = 2
	c = Counter(s)
	for (k, v) in c.items():
		if v > best:
			best = v
	for sd1 in c.keys():
		for sd2 in c.keys():
			if sd1 == sd2:
				continue
			if c[sd1] + c[sd2] <= best:
				continue
			d1_idx = []
			d2_idx = []
			for i in range(n):
				if s[i] == sd1:
					d1_idx.append(i)
				if s[i] == sd2:
					d2_idx.append(i)
			cnt = 0
			last = sd2
			last_i = -1
			i = 0
			j = 0
			while i < len(d1_idx) or j < len(d2_idx):
				if last == sd1:
					while j < len(d2_idx) and d2_idx[j] < last_i:
						j += 1
					if j < len(d2_idx):
						last = sd2
						last_i = d2_idx[j]
						j += 1
						cnt += 1
					else:
						break
				else:
					while i < len(d1_idx) and d1_idx[i] < last_i:
						i += 1
					if i < len(d1_idx):
						last = sd1
						last_i = d1_idx[i]
						i += 1
						cnt += 1
					else:
						break
			if cnt % 2 == 1:
				cnt -= 1
			if cnt > best:
				best = cnt
	return n - best

def main():
	for _ in range(ri()):
		s = rs()
		wi(solve(s))
main()


from math import *
import heapq as h
from collections import Counter
mod = 1000000007

def solve(s, x, y):
	n = len(s)
	res = 0
	f = 1
	for i in range(n):
		if s[i] == x and f == 1:
			f = 0
			res += 1
			continue
		if s[i] == y and f == 0:
			f = 1
			res += 1
	if res % 2:
		if x != y:
			res -= 1
	return res

def pro(s):
	n = len(s)
	maxi = 0
	for i in range(10):
		for j in range(10):
			maxi = max(maxi, solve(s, str(i), str(j)))
	print(n - maxi)
t = int(input())
for i in range(t):
	a = input()
	pro(a)


for t in range(int(input())):
	s = input()
	i = 0
	n = len(s)
	if n <= 2:
		print(0)
		continue
	ans = 2
	freq = {}
	maxF = 1
	for c in s:
		if c not in freq:
			freq[c] = 1
		else:
			freq[c] += 1
			maxF = max(maxF, freq[c])
	ans = max(ans, maxF)
	for i in range(0, 10):
		for j in range(0, 10):
			if i != j:
				x = str(i)
				y = str(j)
				val = 0
				target = x
				for k in range(n):
					if s[k] == target:
						val += 1
						if target == x:
							target = y
						else:
							target = x
				if val % 2 != 0:
					val -= 1
				ans = max(ans, val)
	print(n - ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		s = S()
		s = [int(c) for c in s]
		l = len(s)
		c = [0] * 10
		for t in s:
			c[t] += 1
		r = l - max(c)
		kl = [i for i in range(10) if c[i] > 0]
		for k1 in kl:
			for k2 in kl:
				if k1 == k2:
					continue
				t = 0
				i = 0
				while i < l:
					while i < l:
						if s[i] == k1:
							break
						i += 1
					i += 1
					while i < l:
						if s[i] == k2:
							t += 1
							break
						i += 1
					i += 1
				if r > l - t * 2:
					r = l - t * 2
		rr.append(r)
	return JA(rr, '\n')
print(main())


for _ in range(int(input())):
	s = input()
	digits = '0123456789'
	total = len(s)
	for i in digits:
		for j in digits:
			if i != j:
				count = 0
				order = 0
				for d in s:
					if d == i and (not order):
						count += 1
						order = 1
					elif d == j and order:
						count += 1
						order = 0
				count = count // 2 * 2
				total = min(total, len(s) - count)
	for i in digits:
		total = min(total, len(s) - s.count(i))
	print(total)


for _ in range(int(input())):
	s = input()
	n = len(s)
	if n == 1 or n == 2:
		print(0)
	else:
		dic = {}
		for i in range(n):
			if s[i] in dic:
				dic[s[i]] += 1
			else:
				dic[s[i]] = 1
		mx = 0
		for i in dic.keys():
			mx = max(mx, dic[i])
		ans = n - max(2, mx)
		for i in range(10):
			for j in range(10):
				if i != j:
					fst = i
					cnt = 0
					for k in range(n):
						if int(s[k]) != fst:
							cnt += 1
						elif fst == i:
							fst = j
						else:
							fst = i
					if (n - cnt) % 2 == 1:
						cnt += 1
					ans = min(ans, cnt)
		print(ans)


T = int(input())
l = []
for i in range(10):
	for j in range(i, 10):
		l.append([])
		l[-1].append(str(i))
		l[-1].append(str(j))

def solve():
	if len(set(s)) == 1:
		return 0
	val = 0
	for i in range(55):
		l1 = [x for x in s if x in l[i]]
		if len(l1) == 0:
			continue
		if len(set(l1)) == 1:
			val = max(len(l1), val)
		else:
			newlist = [l1[0]]
			for j in range(1, len(l1)):
				if l1[j] != l1[j - 1]:
					newlist.append(l1[j])
			if len(newlist) % 2 == 1:
				val = max(len(newlist) - 1, val)
			else:
				val = max(len(newlist), val)
	return len(s) - val
for test in range(T):
	s = list(input())
	print(solve())


def numOfChars(s, c):
	ans = 0
	for k in s:
		if k == c:
			ans += 1
	return ans

def calcMaxSubseq(s, charOne, charTwo):
	maxL = 0
	counter = 0
	for c in s:
		if counter == 0 and c == charOne:
			counter = 1
			maxL += 1
		elif counter == 1 and c == charTwo:
			counter = 0
			maxL += 1
	if counter == 1:
		return maxL - 1
	else:
		return maxL
t = int(input())
for i in range(t):
	s = input()
	l = len(s)
	maxL = 0
	print
	for j in range(10):
		maxL = max(maxL, numOfChars(s, str(j)))
		for k in range(j + 1, 10):
			maxL = max(maxL, calcMaxSubseq(s, str(j), str(k)))
			maxL = max(maxL, calcMaxSubseq(s, str(k), str(j)))
	print(l - maxL)


def test(s, c):
	matrix = [[[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]]]
	max = 0
	for i in range(len(s)):
		x = int(s[i])
		for y in range(10):
			if x != y:
				current = matrix[y][x][0]
				if current == y:
					matrix[y][x][0] = x
					matrix[y][x][1] += 1
					if matrix[y][x][1] > max:
						max = matrix[y][x][1]
				current = matrix[x][y][0]
				if current == y or current == -1:
					matrix[x][y][0] = x
					if matrix[x][y][1] > max:
						max = matrix[x][y][1]
	return max * 2

def calc(s):
	positions = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	for i in range(len(s)):
		c = int(s[i])
		positions[c] += 1
	m = max(positions)
	combinations = []
	for i in range(10):
		for j in range(10):
			l1 = positions[i]
			l2 = positions[j]
			if l1 + l2 > m and i != j:
				combinations.append((i, j))
	t = test(s, combinations)
	return m if m > t else t
n = int(input())
for t in range(n):
	s = input()
	print(len(s) - calc(s))


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

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

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
v = [[str(i), str(j)] for i in range(10) for j in range(10) if i != j]
for _ in range(inp()):
	s = insr()
	n = len(s)
	c = Counter(s)
	mx = max(c.values())
	cnt = 0
	for (a, b) in v:
		temp = 0
		cntb = 0
		for i in range(n - 1, -1, -1):
			if s[i] == b:
				cntb = 1
			if s[i] == a:
				if cntb:
					temp += 2
					cntb = 0
			if temp % 2 == 1 and a != b:
				temp -= 1
		cnt = max(temp, cnt)
	print(n - max(cnt, mx))


import sys
import math

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	s = list(SI())
	ans = 2
	d = [[] for i in range(10)]
	dp = [0] * 10
	for i in range(len(s)):
		d[int(s[i])].append(i)
		dp[int(s[i])] += 1
	ans = max(ans, max(dp))
	for i in range(10):
		if len(d[i]) == 0:
			continue
		for j in range(i + 1, 10):
			count = 1
			a = d[i][:]
			b = d[j][:]
			if len(b) == 0:
				continue
			l = 0
			l2 = 0
			temp = -1
			if a[0] < b[0]:
				temp = a[0]
				boo = False
				end = True
			else:
				temp = b[0]
				boo = True
				end = False
			while l < dp[i] and l2 < dp[j]:
				if boo:
					while l < dp[i] and a[l] < temp:
						l += 1
					if l < dp[i]:
						temp = a[l]
						count += 1
						boo = not boo
					else:
						break
				else:
					while l2 < dp[j] and b[l2] < temp:
						l2 += 1
					if l2 < dp[j]:
						temp = b[l2]
						count += 1
						boo = not boo
					else:
						break
			if end != boo:
				count -= 1
			ans = max(ans, count)
	print(len(s) - ans)


for _ in range(int(input())):
	s = input()
	n = len(s)
	s = [int(s[i]) for i in range(n)]
	ans = 2
	for a in range(10):
		for b in range(10):
			temp = 0
			sign = 'a'
			for i in range(n):
				if sign == 'a':
					if s[i] == a:
						temp += 1
						sign = 'b'
				elif s[i] == b:
					temp += 1
					sign = 'a'
			if a == b:
				ans = max(ans, temp)
			else:
				temp -= temp % 2
				ans = max(ans, temp)
	print(n - ans)


def func(a, x, y):
	res = 0
	for c in a:
		if c == x:
			res += 1
			temp = x
			x = y
			y = temp
	if x != y and res % 2 == 1:
		res -= 1
	return res
for _ in range(int(input())):
	a = [int(x) for x in input()]
	ans = 0
	for x in range(10):
		for y in range(10):
			ans = max(ans, func(a, x, y))
	print(len(a) - ans)


import gc

def calc(arr):
	counts = []
	for i in range(10):
		for j in range(10):
			s = i + j
			target = i
			count = 0
			for a in arr:
				if int(a) == target:
					target = s - target
				else:
					count += 1
			if not i == target:
				count += 1
			counts.append(count)
	return min(counts)

def main():
	n = int(input())
	arr = []
	for _ in range(n):
		arr.append(calc(input()))
		gc.collect()
	for a in arr:
		print(a)
main()


for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = 0
	for i in range(10):
		for j in range(10):
			f = True
			c = 0
			for k in range(n):
				if f and int(s[k]) == i:
					c += 1
					f = False
				elif not f and int(s[k]) == j:
					c += 1
					f = True
			if i != j and c % 2:
				c -= 1
			ans = max(ans, c)
	print(n - ans)


def sol(s, x, y):
	c = 0
	for i in s:
		if int(i) == x:
			c += 1
			(x, y) = (y, x)
	if x != y and c & 1:
		c -= 1
	return c
for i in range(int(input())):
	ans = 0
	s = input()
	n = len(s)
	for x in range(10):
		for y in range(10):
			ans = max(ans, sol(s, x, y))
	print(n - ans)


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

def main():
	for _ in range(int(input())):
		s = list((int(x) for x in input()))
		n = len(s)
		c = Counter(s)
		ans = max(c.values())
		for i in range(10):
			for j in range(10):
				ind = 0
				cnt = 0
				digits = [i, j]
				for digit in s:
					if digit == digits[ind]:
						ind ^= 1
						cnt += 1
				if cnt > ans and cnt % 2 == 0:
					ans = cnt
		print(n - 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()


from collections import *
for _ in range(int(input())):
	a = input()
	s = list(a)
	left = a[1:] + a[0]
	right = a[-1] + a[:len(a) - 1]
	if left == right:
		print(0)
	else:
		maxcount = 0
		for i in range(0, 10):
			count = 0
			for j in range(0, len(a)):
				if int(a[j]) == i:
					count += 1
			maxcount = max(count, maxcount)
		temp = 0
		for i in range(0, 10):
			for j in range(0, 10):
				temp = 0
				count = 0
				for k in range(0, len(a)):
					if i != j:
						if int(a[k]) == i and temp == 0:
							temp = 1
							count += 1
						if int(a[k]) == j and temp == 1:
							temp = 0
							count += 1
				if count % 2 == 1:
					maxcount = max(count - 1, maxcount)
				else:
					maxcount = max(maxcount, count)
		print(len(a) - maxcount)


from sys import stdin
input = stdin.readline

def solve(a, b):
	(a, b) = (str(a), str(b))
	curr = None
	first = None
	cnt = 0
	for i in s:
		if not first:
			if a == i:
				first = a
				curr = b
				cnt += 1
			elif b == i:
				first = b
				curr = a
				cnt += 1
		elif curr == i:
			curr = a if curr == b else b
			cnt += 1
	return cnt if curr == first else cnt - 1
for _ in range(int(input())):
	s = input().strip()
	mini = len(s)
	for i in range(10):
		for j in range(i, 10):
			mini = min(mini, len(s) - solve(i, j))
	print(mini)


t = input()
t = int(t)

def solve(s):
	s_list = list(map(int, s))
	real_ans = 0
	for i in range(10):
		for j in range(10):
			ans = 0
			if i == j:
				for n in s_list:
					if n == i:
						ans += 1
			else:
				chk = 0
				for n in s_list:
					if n == i and chk == 0:
						chk = 1
						ans += 1
					elif n == j and chk == 1:
						chk = 0
						ans += 1
					else:
						pass
				if ans % 2 == 1:
					ans = 0
			if ans > real_ans:
				real_ans = ans
	print(len(s) - real_ans)
for i in range(t):
	s = input()
	solve(s)


def func(i, j, s):
	p = [i, j]
	need = 0
	count = 0
	for k in s:
		if k == p[need]:
			count += 1
			need ^= 1
	if i != j and count % 2 == 1:
		count -= 1
	return count
for _ in range(int(input())):
	s = input()
	ans = 2
	for i in range(10):
		for j in range(10):
			ans = max(ans, func(str(i), str(j), s))
	print(len(s) - ans)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

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

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

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('0')
file = 1

def solve():
	for _ in range(ii()):
		f = {}
		for i in range(10):
			f[i] = []
		s = si()
		n = len(s)
		for i in range(n):
			f[bo(s[i])].append(i)
		ans = 0
		x = 0
		for i in range(10):
			if len(f[i]) > ans:
				ans = len(f[i])
		ans1 = 0
		for i in range(10):
			for j in range(10):
				if i == j:
					continue
				l1 = 0
				l2 = 0
				a = f[i]
				b = f[j]
				cnt = 0
				f1 = 0
				while l1 < len(a) and l2 < len(b):
					if a[l1] < b[l2]:
						l1 += 1
						if f1 == 0:
							cnt += 1
							f1 ^= 1
					else:
						l2 += 1
						if f1:
							cnt += 1
							f1 ^= 1
				if l2 < len(b):
					if f1:
						cnt += 1
				if cnt > ans1:
					ans1 = cnt
					x1 = i
					x2 = j
		print(n - max(ans, ans1))
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = len(s) - 1
	for i in range(0, 10):
		cnt = 0
		for j in s:
			if j != str(i):
				cnt += 1
		ans = min(ans, cnt)
	for i in range(0, 10):
		for j in range(0, 10):
			if i == j:
				continue
			isi = True
			cnt = 0
			for k in s:
				if isi and k == str(i):
					cnt += 1
					isi = not isi
				elif not isi and k == str(j):
					cnt += 1
					isi = not isi
			if cnt % 2 != 0:
				cnt -= 1
			ans = min(ans, n - cnt)
	print(ans)


t = int(input())
for i in range(t):
	a = input()
	b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
	k = 0
	for j in range(10):
		for l in range(10):
			q = str(b[j])
			w = str(b[l])
			e = 0
			r = 0
			d = 0
			for f in a:
				d += 1
				if f == q and e == r:
					e += 1
				elif f == w and e != r:
					r += 1
			if q == w:
				if e + r > k:
					k = e + r
			elif e + r - (e + r) % 2 > k:
				k = e + r - (e + r) % 2
	print(d - k)


for _ in range(int(input())):
	n = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			tmp = str(i)
			l = 0
			for c in n:
				if tmp == c:
					l += 1
					tmp = str(j) if tmp == str(i) else str(i)
			if l & 1 and i != j:
				l -= 1
			ans = max(ans, l)
	print(len(n) - ans)


import math

def is_good(x):
	x = str(x)
	return x[1:] + x[0] == x[-1] + x[:-1]

def best_if_even(s, i, j):
	i = str(i)
	j = str(j)
	taken = None
	skip = 0
	for c in s:
		if taken is None and c == i:
			taken = 0
		elif taken is None and c == j:
			taken = 1
		elif taken == 0 and c == j:
			taken = 1
		elif taken == 1 and c == i:
			taken = 0
		else:
			skip += 1
	if (len(s) - skip) % 2 == 1:
		skip += 1
	return skip

def main():
	for _ in range(int(input())):
		s = input()
		ans = len(s)
		for i in range(10):
			ans = min(ans, sum((c != str(i) for c in s)))
			for j in range(10):
				ans = min(ans, best_if_even(s, i, j))
		print(ans)
main()


for _ in range(int(input())):
	s = input()
	ans = 1000000
	for i in range(10):
		temp = 0
		for j in s:
			if j != str(i):
				temp += 1
		ans = min(ans, temp)
	for i in range(10):
		for j in range(10):
			temp = 0
			l = True
			for k in s:
				if l:
					if k != str(i):
						temp += 1
					else:
						l = False
				elif k != str(j):
					temp += 1
				else:
					l = True
			if (len(s) - temp) % 2 != 0:
				ans = min(ans, temp + 1)
			else:
				ans = min(ans, temp)
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	pair = []
	res = []
	for i in range(10):
		for j in range(10):
			pair.append([i, j])
	for i in range(100):
		turn = pair[i][0]
		c = 0
		for j in range(len(s)):
			if int(s[j]) != turn:
				c += 1
			elif turn == pair[i][0]:
				turn = pair[i][1]
			else:
				turn = pair[i][0]
		if (len(s) - c) % 2 == 0:
			res.append(c)
		if (len(s) - c) % 2 != 0 and pair[i][0] == pair[i][1]:
			res.append(c)
	print(min(res))


def main():
	t = int(input())
	for i in range(t):
		s = input()
		n = len(s)
		ar = [[0, ''] for i in range(100)]
		al = '0123456789'
		ar2 = [0] * 10
		for i in s:
			ar2[int(i)] += 1
			for j in al:
				ind = int(''.join(sorted([i, j])))
				if ar[ind][1] == '' or ar[ind][1] != i:
					ar[ind][1] = i
					ar[ind][0] += 1
		for i in range(100):
			ar[i][0] -= ar[i][0] & 1
		print(n - max(max(ar2), max(ar, key=lambda x: x[0])[0]))
main()


T = int(input())
for _ in range(0, T):
	s = input()
	n = len(s)
	pre = [0] * 10
	for i in range(0, len(s)):
		pre[ord(s[i]) - 48] += 1
	ans = n - 2
	for i in range(10):
		ans = min(ans, n - pre[i])
	for i in range(10):
		for j in range(10):
			k1 = str(i)
			k2 = str(j)
			c = 0
			turn = 0
			for k in range(0, len(s)):
				if turn == 0 and s[k] == k1:
					turn = 1
					c += 1
				elif turn == 1 and s[k] == k2:
					turn = 0
					c += 1
			if c % 2 != 0:
				c -= 1
			ans = min(ans, n - c)
	print(ans)


import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
input = stdin.readline
letters = ascii_letters[:26]

def find(p, t, rev):
	if not rev:
		for i in range(len(t) - len(p)):
			if p == t[i:i + len(p)]:
				return i
		return -1
	else:
		for i in range(len(t) - len(p), -1, -1):
			if p == t[i:i + len(p)]:
				return i
		return -1
for _ in range(int(input())):
	x = list(input().strip())
	res = 99999999
	for k in range(10):
		for g in range(10):
			need = 0
			cnt = 0
			for i in x:
				if need:
					if i == str(g):
						need = (1 + need) % 2
						cnt += 1
				elif i == str(k):
					need = (1 + need) % 2
					cnt += 1
			if cnt % 2:
				continue
			res = min(res, len(x) - cnt)
	for k in range(10):
		res = min(res, len(x) - x.count(str(k)))
	res = min(res, len(x) - 2)
	print(res)


for m in [*open(0)][1:]:
	kj = [0] * 100
	for i in map(int, m[:-1]):
		for j in range(10):
			kj[10 * i + j] = kj[10 * j + i] + 1
	print(len(m) - 1 - max(max(kj) & ~1, *kj[::11]))


t = int(input())

def ask(p, s):
	need = 0
	cnt = 0
	for v in s:
		if v == p[need]:
			cnt += 1
			need ^= 1
	if p[0] != p[1] and cnt % 2 == 1:
		cnt -= 1
	return cnt
for _ in range(t):
	s = input()
	ans = 2
	for i in range(10):
		for j in range(10):
			ans = max(ans, ask((str(i), str(j)), s))
	print(len(s) - ans)


from sys import stdin, stdout
for _ in range(int(input())):
	s = input().strip()
	n = len(s)
	ans = 0
	for i in range(10):
		i = str(i)
		for j in range(10):
			j = str(j)
			(c1, c2) = (0, 0)
			for k in s:
				if k == i and c1 == c2:
					c1 += 1
				elif k == j and c1 > c2:
					c2 += 1
			c3 = 0
			if i == j:
				c3 = c2 + c1
			ans = max(c2 * 2, c3, ans)
	print(n - ans)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi
import heapq, random

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

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

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

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_le(a, x):
	i = bi.bisect_right(a, x)
	if i:
		return i - 1
	else:
		return -1

def main():
	try:
		n = list(map(int, input()))
		ans = 10000000.0
		for i in range(10):
			for j in range(10):
				if i == j:
					count = 0
					for x in range(len(n)):
						if n[x] == i:
							count += 1
					ans = min(len(n) - count, ans)
				else:
					count = 0
					q = 0
					for x in range(len(n)):
						if q == 0:
							if n[x] == i:
								count += 1
								q = 1
						if q == 1:
							if n[x] == j:
								count += 1
								q = 0
					if count & 1 == 1:
						count -= 1
					ans = min(ans, len(n) - count)
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


t = int(input())
for i in range(t):
	s = str(input())
	l = len(s)
	a0 = a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = 0
	a = l - 2
	for i in s:
		if i == '0':
			a0 = a0 + 1
		elif i == '1':
			a1 = a1 + 1
		elif i == '2':
			a2 = a2 + 1
		elif i == '3':
			a3 = a3 + 1
		elif i == '4':
			a4 = a4 + 1
		elif i == '5':
			a5 = a5 + 1
		elif i == '6':
			a6 = a6 + 1
		elif i == '7':
			a7 = a7 + 1
		elif i == '8':
			a8 = a8 + 1
		else:
			a9 = a9 + 1
	bm = max(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)
	b = l - bm
	m = 0
	for i in range(10):
		for j in range(10):
			c = 0
			if i != j:
				for x in s:
					y = int(x)
					if c % 2 == 0 and y == i:
						c = c + 1
					elif c % 2 == 1 and y == j:
						c = c + 1
				if c > m:
					m = c
	m = m // 2
	m = m * 2
	d = l - m
	print(max(min(a, b, d), 0))


from bisect import bisect_left, bisect_right

class Result:

	def __init__(self, index, value):
		self.index = index
		self.value = value

class BinarySearch:

	def __init__(self):
		pass

	@staticmethod
	def greater_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_right(func, num)
			if index == len(func):
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(omega) <= num:
				return Result(None, None)
			while alpha < omega:
				if func(alpha) > num:
					return Result(alpha, func(alpha))
				if omega == alpha + 1:
					return Result(omega, func(omega))
				mid = (alpha + omega) // 2
				if func(mid) > num:
					omega = mid
				else:
					alpha = mid

	@staticmethod
	def less_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_left(func, num) - 1
			if index == -1:
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(alpha) >= num:
				return Result(None, None)
			while alpha < omega:
				if func(omega) < num:
					return Result(omega, func(omega))
				if omega == alpha + 1:
					return Result(alpha, func(alpha))
				mid = (alpha + omega) // 2
				if func(mid) < num:
					alpha = mid
				else:
					omega = mid
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')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	s = input()
	ans = 1
	cur = 1
	cc = s[0]
	for i in range(1, len(s)):
		if s[i] == cc:
			cur += 1
		else:
			ans = max(ans, cur)
			cur = 1
			cc = s[i]
	ans = max(ans, cur)
	ind = [[] for __ in range(10)]
	for i in range(len(s)):
		ind[int(s[i])] += [i]
	for i in range(10):
		ans = max(ans, len(ind[i]))
	bs = BinarySearch()
	for i in range(10):
		for j in range(10):
			start = -1
			anss = 0
			while True:
				next = bs.greater_than(start, ind[i]).value
				if next is None:
					break
				nextnext = bs.greater_than(next, ind[j]).value
				if nextnext is None:
					break
				anss += 2
				start = nextnext
			ans = max(ans, anss)
	print(len(s) - ans)


import random

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

def lcm(a, b):
	return a * b / gcd(a, b)
for _ in range(int(input())):
	s = input()
	ans = len(s)
	for i in range(10):
		for j in range(i, 10):
			curr = str(i)
			curr2 = str(j)
			m = 0
			m2 = 0
			for k in s:
				if k == curr:
					m += 1
					if curr == str(i):
						curr = str(j)
					else:
						curr = str(i)
				if k == curr2:
					m2 += 1
					if curr2 == str(i):
						curr2 = str(j)
					else:
						curr2 = str(i)
			if curr == str(j) and i != j:
				m -= 1
			if curr2 == str(i) and i != j:
				m2 -= 1
			ans = min(len(s) - m, ans)
			ans = min(len(s) - m2, ans)
	print(ans)


def calc(s, x, y):
	val = 0
	for c in s:
		if int(c) == x:
			val += 1
			(x, y) = (y, x)
	if x != y and val % 2:
		val -= 1
	return val
t = int(input())
for T in range(t):
	s = input()
	res = 0
	for i in range(10):
		for j in range(10):
			res = max(res, calc(s, i, j))
	print(len(s) - res)


for _ in range(int(input())):
	s = input()
	som = 0
	for i in range(10):
		for j in range(10):
			f = 0
			m = 0
			for k in s:
				if f == 0:
					if int(k) == i:
						m = m + 1
						f = 1
				elif int(k) == j:
					m = m + 1
					f = 0
			if i != j:
				m = m - m % 2
			som = max(som, m)
	print(len(s) - som)


def find(s, a, b):
	ans = 0
	for c in s:
		if a == c:
			(a, b) = (b, a)
			ans += 1
	if a != b and ans % 2 == 1:
		ans -= 1
	return ans

def slove():
	s = input()
	ans = 0
	for i in range(0, 10):
		for j in range(0, 10):
			ans = max(ans, find(s, str(i), str(j)))
	print(len(s) - ans)

def main():
	t = int(input())
	while t > 0:
		slove()
		t -= 1
main()


from sys import stdin, stdout
import bisect
import math

def st():
	return list(stdin.readline().strip())

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

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

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

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

def soe(limit):
	l = [1] * (limit + 1)
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
		a *= a
		n = n >> 1
	return r

def solve():
	s = input()
	n = len(s)
	d = {}
	for i in s:
		d[i] = d.get(i, 0) + 1
	mi = float('-inf')
	for i in d:
		if d[i] > mi:
			mi = d[i]
	for i in range(10):
		for j in range(10):
			c = 0
			for k in s:
				if c % 2:
					if k == str(j):
						c += 1
				elif k == str(i):
					c += 1
			if c & 1:
				c -= 1
			mi = max(c, mi)
	pr(n - mi)
for _ in range(inp()):
	solve()


import math

def solve(s, i, j):
	toRemove = 0
	for sub in s:
		if int(sub) == i:
			toRemove += 1
			(i, j) = (j, i)
	if toRemove % 2 == 1 and i != j:
		toRemove -= 1
	return toRemove
for _ in range(int(input())):
	ans = 0
	string = input()
	for i in range(10):
		for j in range(10):
			ans = max(ans, solve(string, i, j))
	print(len(string) - ans)


import sys
input = sys.stdin.readline
ins = lambda : input().rstrip()
ini = lambda : int(input().rstrip())
inm = lambda : map(int, input().rstrip().split())
inl = lambda : list(map(int, input().split()))
out = lambda x, s='\n': print(s.join(map(str, x)))
output = []
t = ini()
for _ in range(t):
	s = ins()
	ans = 0
	for i in range(10):
		for j in range(10):
			k = 1
			count = 0
			for n in s:
				if k == 1:
					if n == str(i):
						count += 1
						k = -k
				elif n == str(j):
					count += 1
					k = -k
			if i == j:
				ans = max(ans, count)
			else:
				count += -1 if count % 2 else 0
				ans = max(ans, count)
	output.append(len(s) - ans)
out(output)


from sys import stdin, stdout
for query in range(int(stdin.readline())):
	s = [int(x) for x in list(stdin.readline().strip())]
	n = len(s)
	a = []
	best = 0
	for x in range(10):
		for y in range(10):
			if x != y:
				a.append((x, y))
	for x in range(10):
		count = 0
		for y in s:
			if x == y:
				count += 1
		best = max(best, count)
	for x in a:
		pointer = 0
		count = 0
		for y in s:
			if y == x[pointer]:
				count += 1
				pointer = (pointer + 1) % 2
		if count % 2 == 1:
			count -= 1
		best = max(best, count)
	stdout.write(str(n - best) + '\n')


from collections import defaultdict
from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	s = stdin.readline().strip()
	d = defaultdict(int)
	for c in s:
		d[c] += 1
	ma = 0
	for k in d:
		ma = max(ma, d[k])
	ans = len(s) - ma
	for i in range(10):
		for j in range(10):
			m = [chr(ord('0') + i), chr(ord('0') + j)]
			idx = 0
			cnt = 0
			for c in s:
				if c == m[idx]:
					cnt += 1
					idx = 1 - idx
			if cnt % 2 == 1:
				cnt -= 1
			ans = min(ans, len(s) - cnt)
	print(ans)


t = int(input())
for _ in range(t):
	st = input()
	sp = list(set(st))
	moc = 0
	mm = 0
	for i in sp:
		for j in sp:
			if i == j:
				coc = st.count(i)
				mm = max(mm, coc)
				continue
			bo = False
			coc = 0
			for s in st:
				if not bo and s == i:
					bo = True
				elif bo and s == j:
					bo = False
					coc += 1
			moc = max(moc, coc)
	print(len(st) - max(2 * moc, mm))


from sys import stdin, stdout
from collections import Counter

def sl(A, B, C):
	S = 0
	for i in A:
		if S % 2 != 0 and i == B:
			S += 1
		if S % 2 == 0 and i == C:
			S += 1
	return S

def ssd(A, B, C):
	if B not in A and C not in A:
		return 0
	return max(sl(A, B, C), sl(A, C, B))

def find(S):
	A = Counter(S)
	M = max(A.values())
	for i in range(10):
		for j in range(i + 1, 10):
			R = ssd(S, str(i), str(j))
			M = max(M, R // 2 * 2)
	return len(S) - M

def main():
	for _ in range(int(stdin.readline())):
		S = stdin.readline().strip()
		print(find(S))
main()


def check(pat, strr):
	idx = 0
	i = 0
	ans = 0
	while i < len(strr):
		if strr[i] == pat[0]:
			idx = 1
		elif strr[i] == pat[1]:
			if idx > 0:
				idx -= 1
				ans += 2
		i += 1
	return len(strr) - ans
for vishal in range(int(input())):
	s = input()
	d = {}
	for i in s:
		try:
			d[i] += 1
		except:
			d[i] = 1
	ans = len(s) - 2
	ans = min(ans, len(s) - max([d[j] for j in d.keys()]))
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			ans = min(ans, check(str(i) + str(j), s))
	print(ans)


def solve(s):
	n = len(s)
	ans = 1000000
	for i in range(10):
		d = 0
		for j in s:
			if j == str(i):
				d += 1
		ans = min(ans, n - d)
		for j in range(10):
			if i == j:
				continue
			p = str(i) + str(j)
			k = 0
			for l in range(n):
				if s[l] == p[k % 2]:
					k += 1
			v = k // 2 * 2
			ans = min(ans, n - v)
	return ans
for _ in range(int(input())):
	print(solve(input()))


for _ in range(int(input())):
	n = input()
	ans = 2 * int(100000.0)
	for pair in range(100):
		i = 0
		s = str(pair)
		if len(s) == 1:
			s = '0' + s
		d = 0
		for j in n:
			if j != s[i]:
				d += 1
			else:
				i = 1 - i
		if i == 1 and s[0] != s[1]:
			d += 1
		ans = min(ans, d)
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	best = max(len(s) - 2, 0)
	if best == 0:
		print(0)
		continue
	counter = [0] * 10
	for char in s:
		counter[int(char)] += 1
	onedigitbest = len(s) - max(counter)
	if onedigitbest < best:
		best = onedigitbest
	for j in range(10):
		if not counter[j] or 2 * counter[j] <= len(s) - best:
			continue
		for k in range(j + 1, 10):
			if not counter[k] or 2 * counter[k] <= len(s) - best:
				continue
			a = s.index(str(j))
			b = s.index(str(k))
			if a < b:
				start = str(j)
			else:
				start = str(k)
			total = 0
			for char in s:
				if char == start:
					total += 1
					if start == str(j):
						start = str(k)
					else:
						start = str(j)
			if total % 2 == 1:
				total -= 1
			if len(s) - total < best:
				best = len(s) - total
	print(best)


t = int(input())

def subseq(a, b, s):
	ans = 0
	i = 0
	flag = 0
	while i < len(s):
		if flag == 0:
			if s[i] == a:
				ans += 1
				flag += 1
		elif s[i] == b:
			ans += 1
			flag += 1
		flag %= 2
		i += 1
	if ans % 2 == 0:
		return ans
	elif a == b:
		return ans
	else:
		return ans - 1

def solve(a):
	ans = 10 ** 9
	for i in range(10):
		for j in range(10):
			ans = min(ans, len(a) - subseq(str(i), str(j), a))
	print(ans)
while t:
	t -= 1
	a = input()
	solve(a)


import math
import copy
t = int(input())
for q in range(t):
	s = [int(x) for x in input()]
	x = [0] * 10
	for i in range(10):
		x[i] = s.count(i)
	mini = 100000000000000
	for i in range(10):
		for j in range(10):
			now = 0
			find = i
			for w in s:
				if w == find:
					if find == i:
						find = j
					else:
						find = i
				else:
					now += 1
			if find != i:
				now += 1
			mini = min(mini, now)
	print(mini)


z = input
for _ in range(int(z())):
	(l, a) = (z(), 0)
	for i in range(10):
		for j in range(10):
			(t, t1, c) = (i, j, 0)
			for k in l:
				if int(k) == t:
					c += 1
					(t, t1) = (t1, t)
			if c % 2 and i != j:
				c -= 1
			a = max(a, c)
	print(len(l) - a)


def solution(S):
	counter = [[0] * 10 for _ in range(10)]
	expect_smaller = [[True] * 10 for _ in range(10)]
	for i in range(10):
		for j in range(10):
			if i > j:
				expect_smaller[i][j] = False
	for s in S:
		sc = int(s)
		for i in range(sc):
			if expect_smaller[i][sc]:
				expect_smaller[i][sc] = not expect_smaller[i][sc]
				counter[i][sc] += 1
			if expect_smaller[sc][i]:
				expect_smaller[sc][i] = not expect_smaller[sc][i]
				counter[sc][i] += 1
		counter[sc][sc] += 1
		for i in range(sc + 1, 10):
			if not expect_smaller[i][sc]:
				expect_smaller[i][sc] = not expect_smaller[i][sc]
				counter[i][sc] += 1
			if not expect_smaller[sc][i]:
				expect_smaller[sc][i] = not expect_smaller[sc][i]
				counter[sc][i] += 1
	(mi, mj, m) = (0, 0, 0)
	for i in range(10):
		for j in range(10):
			val = counter[i][j]
			if i != j and val % 2 == 1:
				val -= 1
			if val > m:
				(mi, mj, m) = (i, j, val)
	return len(S) - m
t = int(input())
for i in range(t):
	s = input()
	print(solution(s))


t = int(input())

def swap(x, y):
	return (y, x)
for _ in range(t):
	s = input()
	mx = 0
	for i in range(10):
		for j in range(10):
			cur = 0
			(x, y) = (i, j)
			for a in s:
				if int(a) == x:
					cur += 1
					(x, y) = swap(x, y)
			if cur % 2 == 1 and i != j:
				cur -= 1
			mx = max(mx, cur)
	print(len(s) - mx)


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(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
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		s = sin()
		c = Counter(s)
		ans = max(c.values())
		mx = 0
		n = len(s)
		for i in range(10):
			for j in range(10):
				if i != j:
					k = 0
					res = 0
					flag = 0
					while k < n:
						if s[k] == str(i) and flag == 0:
							flag = 1
						elif s[k] == str(j) and flag == 1:
							flag = 0
							res += 2
						k += 1
					mx = max(res, mx)
		print(n - max(ans, mx))
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')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from collections import deque
input = sys.stdin.readline
t = int(input())
sub = []
for i in range(10):
	for j in range(10):
		sub.append((i, j))
for _ in range(t):
	s = list(input())
	s = [int(s[i]) for i in range(len(s) - 1)]
	ans = float('inf')
	if len(s) <= 2:
		print(0)
		continue
	for (a, b) in sub:
		new = []
		for i in s:
			if i == a or i == b:
				new.append(i)
		n = len(new)
		c = len(s) - n
		new = deque(new)
		d = (a, b)
		nn = []
		while new:
			curr = new.popleft()
			if nn:
				if nn[-1] != curr:
					nn.append(curr)
			else:
				nn.append(curr)
		c += n - len(nn)
		if len(nn) % 2:
			c += 1
		ans = min(ans, c)
	for i in range(10):
		ans = min(ans, len(s) - s.count(i))
	print(ans)


for t in range(int(input())):
	alpha = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	s = input()
	ans = 10 ** 6
	for c1 in alpha:
		for c2 in alpha:
			l = []
			count = 0
			for i in range(len(s)):
				if s[i] == c1 and count == 0:
					l.append(i)
					count = 1
				elif s[i] == c2 and count == 1:
					l.append(i)
					count = 0
			if len(l) % 2 == 0:
				ans = min(ans, len(s) - len(l))
			elif c1 != c2:
				ans = min(ans, len(s) - len(l) + 1 * (len(l) != 1))
			else:
				ans = min(ans, len(s) - len(l))
	print(ans)


from sys import stdout, stdin
(_input, _print) = (stdin.readline, stdout.write)
(_len, _range, _list, _int) = (len, range, list, int)
from collections import Counter
from itertools import combinations

def solution():
	for _ in _range(_int(_input())):
		s = _list(_input())
		len_s = _len(s)
		z = Counter(s)
		ans = len_s - z.most_common(1)[0][1]
		pairs = combinations(_list(z), 2)
		for pair in pairs:
			n = 0
			c = None
			start_c = -1
			for i in s:
				if c is None:
					if i == pair[0]:
						c = 1
						start_c = 0
						continue
					if i == pair[1]:
						c = 0
						start_c = 1
						continue
					n += 1
				elif i == pair[c]:
					c += 1
					c %= 2
				else:
					n += 1
			if start_c != c:
				n += 1
			if n < ans:
				ans = n
		print(ans - 1)
solution()


from sys import stdin, stdout
import math
from collections import Counter, defaultdict
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()

def case():
	s = S()
	n = len(s)
	d = Counter(s)
	ans = n - max(d.values())
	for i in range(10):
		for j in range(10):
			f = 0
			x = 0
			for k in range(n):
				if f == 0 and s[k] == str(i):
					x += 1
					f = 1
				elif f == 1 and s[k] == str(j):
					x += 1
					f = 0
			if x % 2 != 0:
				x -= 1
			ans = min(ans, n - x)
	print(ans)
for _ in range(IN()):
	case()


def test_case():
	s = input()
	n = len(s)
	ans = n - 2
	for a in range(10):
		for b in range(10):
			cur = 0
			want = a
			for c in s:
				if ord(c) - ord('0') == want:
					want = b if a == want else a
				else:
					cur += 1
			if (n - cur) % 2 == 1 and a != b:
				cur += 1
			ans = min(ans, cur)
	print(ans)
for i in range(int(input())):
	test_case()


t = int(input())
for _ in range(t):
	l = input()
	ones = [0 for i in range(10)]
	val = 0
	for char in l:
		ones[ord(char) - ord('0')] += 1
		val = max(val, ones[ord(char) - ord('0')])
	for i in range(10):
		if ones[i] > val // 2:
			for j in range(10):
				if i != j and ones[j] > val // 2:
					a = False
					b = 0
					for k in range(len(l)):
						if a == False and ord(l[k]) - ord('0') == i:
							a = True
						if a and ord(l[k]) - ord('0') == j:
							a = False
							b += 2
					val = max(val, b)
	print(len(l) - val)


t = int(input())
for tc in range(t):
	s = str(input())
	freq = {}
	for i in range(10):
		freq[str(i)] = 0
	for i in s:
		freq[i] += 1
	res = len(s) - max(freq.values())
	for i in range(10):
		for j in range(10):
			flag = 0
			cnt = 0
			for k in s:
				if flag == 0 and k == str(i):
					flag = 1
					cnt += 1
				elif flag == 1 and k == str(j):
					flag = 0
					cnt += 1
			if cnt % 2 == 1:
				cnt -= 1
			res = min(res, len(s) - cnt)
	print(res)


import sys
import collections
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		S = input().strip()
		c = collections.Counter(S)
		ans = len(S) - c.most_common()[0][1]
		for i in range(10):
			for j in range(10):
				if i == j:
					continue
				cnt = 0
				next = str(i)
				for s in S:
					if s != next:
						cnt += 1
					elif s == str(i):
						next = str(j)
					else:
						next = str(i)
				if next == str(j):
					cnt += 1
				ans = min(ans, cnt)
		print(ans)
main()


import sys
readline = sys.stdin.readline

def solve():
	S = readline().rstrip()
	N = len(S)
	odds = [S.count(str(i)) for i in range(10)]
	odds_max = max(odds)
	ans = N - max(odds)
	for i in range(10):
		if odds[i] * 2 <= odds_max:
			continue
		for j in range(i + 1, 10):
			if odds[j] * 2 <= odds_max:
				continue
			count = 0
			last = None
			(_i, _j) = (str(i), str(j))
			for (v, c) in enumerate(S):
				if c != last:
					if c == _i:
						last = _i
						count += 1
					elif c == _j:
						last = _j
						count += 1
			ans = min(ans, N - count // 2 * 2)
	print(ans)
T = int(readline())
for t in range(T):
	solve()


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

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

def solve(a, b):
	res = 0
	for it in s:
		if it == a:
			res += 1
			(a, b) = (b, a)
	if res % 2 != 0 and a != b:
		res -= 1
	return res
for _ in range(int(input())):
	s = input()
	m = 0
	ans = 0
	for i in range(10):
		for j in range(10):
			ans = max(ans, solve(str(i), str(j)))
	print(len(s) - ans)


import sys
input = sys.stdin.readline

def name(arr):
	patterns = {}
	highest = 0
	count = 0
	for i in range(10):
		for j in range(10):
			first = 0
			found = False
			for char in arr[:-1]:
				if i == j:
					if char == str(i):
						count += 1
				else:
					if first != 1:
						if char == str(i):
							first = 1
					elif first == 1:
						if char == str(j):
							first = 0
							found = True
					if found:
						count += 2
						found = False
			if count > highest:
				highest = count
			count = 0
	return len(arr) - 1 - highest

def solution():
	arr = input()
	print(name(arr))
t = int(input())
for i in range(0, t):
	solution()


import sys
from collections import Counter

def func(S, i, j):
	b = False
	a = 0
	for c in S:
		if c == i:
			b = True
		elif c == j and b:
			b = False
			a += 1
	return a

def main():
	T = int(sys.stdin.readline())
	for t in range(T):
		S = sys.stdin.readline().strip()
		a = Counter(S).most_common(1)[0][1]
		for i in range(10):
			for j in range(10):
				if i == j:
					continue
				x = func(S, str(i), str(j))
				a = max(a, 2 * x)
		print(len(S) - a)
main()


from sys import stdin, stdout
import math

def solve():
	ans = 0
	s = input()
	l = len(s)
	d = {}
	c = ''
	for i in s:
		if i in d:
			d[i] += 1
			if d[i] > ans:
				ans = d[i]
		else:
			d[i] = 1
	for i in range(10):
		for j in range(10):
			if i != j:
				cur = 0
				for k in range(l):
					if cur & 1:
						if s[k] == str(i):
							cur += 1
					elif s[k] == str(j):
						cur += 1
				cur -= cur % 2
				ans = max(ans, cur)
	print(l - ans)
tt = 1
tt = int(input())
for __ in range(tt):
	solve()


from collections import Counter
for _ in range(int(input())):
	s = list(input())
	n = len(s)
	c = Counter(s)
	m = 0
	for i in c:
		m = max(m, c[i])
	ans = min(n - 2, n - m)
	count = {}
	numbers = '0123456789'
	for i in numbers:
		flag = False
		for j in range(n):
			if s[j] == i:
				found = {}
				flag = True
			elif flag:
				if s[j] not in found:
					found[s[j]] = 1
					if i + s[j] not in count:
						count[i + s[j]] = 1
					else:
						count[i + s[j]] += 1
	m = 0
	for i in count:
		m = max(m, count[i])
	print(min(ans, n - 2 * m, n - 2))


import sys
import heapq
from collections import deque
from collections import defaultdict
I = lambda : list(map(int, input().split(' ')))
import time

def largeS(string):
	lst = list('0123456789')
	mm = 2
	for a in lst:
		for b in lst:
			if a == b:
				continue
			t = 0
			for ele in string:
				if t % 2 == 0 and ele == a:
					t += 1
				elif t % 2 == 1 and ele == b:
					t += 1
			t = t - t % 2
			mm = max(t, mm)
	for a in lst:
		t = 0
		for ele in string:
			if ele == a:
				t += 1
		mm = max(t, mm)
	return len(string) - mm
for _ in range(int(input())):
	s = input()
	if len(s) == 1 or len(s) == 2:
		print(0)
		continue
	print(largeS(s))


import io
import os
import sys
from collections import deque, defaultdict

def _input():
	x = sys.stdin.readline()
	x = x.replace('\r', '')
	x = x.replace('\n', '')
	return x
if 'STDINPUT' not in os.environ:
	input = _input
else:
	print('Standard input')

def solve():
	x = [int(i) for i in input()]
	pattern = []
	for i in range(10):
		for j in range(10):
			pattern.append([i, j])
	ans = 10 ** 10
	cans = 0
	g = 0
	for i in pattern:
		for j in x:
			if j == i[g % 2]:
				cans += 1
				g += 1
		ans = min(ans, len(x) - (cans - cans % 2 if not i[0] == i[1] else cans))
		cans = 0
		g = 0
	print(ans)
test_cases = True
if test_cases:
	_q = int(input())
	for _ in range(_q):
		solve()
else:
	solve()


def get_a(even, odd, a):
	flag = 0
	b = []
	for i in range(0, len(a)):
		if flag == 0 and a[i] == even:
			b.append(even)
			flag = 1
		elif flag == 1 and a[i] == odd:
			b.append(odd)
			flag = 0
	return b

def process(n, a):
	a = list(a)
	m = 0
	for i in range(0, 10):
		for j in range(0, 10):
			a1 = get_a(str(i), str(j), a)
			if len(a1) % 2 == 0 or i == j:
				m = max(m, len(a1))
	return len(a) - m
t = int(input())
for i in range(0, t):
	a = input()
	print(process(len(a), a))


import sys, collections
mod = 10 ** 9 + 7
INF = float('inf')

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

def inpl():
	return list(map(int, sys.stdin.readline().split()))
t = inp()
for _ in range(t):
	s = input()
	cnt = [[0 for _ in range(10)] for i in range(10)]
	fl = [[False for _ in range(10)] for i in range(10)]
	for (i, x) in enumerate(s):
		now = int(x)
		for j in range(10):
			if now == j:
				continue
			fl[now][j] = True
		for j in range(10):
			if now == j:
				continue
			if fl[j][now]:
				cnt[j][now] += 2
				fl[j][now] = False
	res1 = 0
	for i in range(10):
		for j in range(10):
			res1 = max(res1, cnt[i][j])
	c = collections.Counter(s)
	res2 = max(c.values())
	res = max(res1, res2, 2)
	print(len(s) - res)


t = int(input())
for t_ in range(t):
	s = input()
	best = 0
	for a in range(10):
		for b in range(10):
			c = 0
			state = 0
			for n in range(len(s)):
				if s[n] == str(a) and state == 0:
					c += 1
					state = 1
				elif s[n] == str(b) and state == 1:
					c += 1
					state = 0
			if a != b and state == 1:
				c -= 1
			if c > best:
				best = c
	print(len(s) - best)


for _ in range(int(input())):
	s = input()
	a = []
	for i in s:
		a.append(int(i))
	b = []
	n = len(s)
	for i in range(10):
		for j in range(10):
			check = False
			cnt = 0
			st = 11
			nd = 11
			for k in a:
				if k == i or k == j:
					if k == i:
						st = i
						nd = j
					else:
						st = j
						nd = i
					break
			if st != 11:
				for k in a:
					if k == st and (not check):
						cnt += 1
						check = True
					elif k == nd and check:
						cnt += 1
						check = False
			if st != nd and cnt % 2 != 0:
				cnt -= 1
			b.append(cnt)
	print(n - max(b))


n = int(input())
for i in range(n):
	s = input()
	l = len(s)
	d = dict()
	for i in '0123456789':
		d[i] = 0
	for i in s:
		d[i] = d[i] + 1
	maxi = 0
	for i in '0123456789':
		if d[i] > maxi:
			maxi = d[i]
	maxi1 = 0
	for i in '0123456789':
		for j in '0123456789':
			if i == j:
				continue
			count = 0
			flag = 1
			for k in s:
				if k == i and flag == 1:
					flag = 0
				if k == j and flag == 0:
					count = count + 1
					flag = 1
			if count * 2 >= maxi1:
				maxi1 = count * 2
	print(min(l - maxi, l - maxi1))


def main(x, y):
	c = x
	count = 0
	for i in range(n):
		if s[i] == c:
			count += 1
			if c == x:
				c = y
			else:
				c = x
	if count & 1:
		if x == y:
			return count
		return count - 1
	return count
a = '0123456789'
for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = 0
	for i in a:
		for j in a:
			ans = max(ans, main(i, j))
	print(n - ans)


t = int(input())
for _ in range(t):
	s = list(input())
	n = len(s)
	ans = n - 2
	lis = [str(i) for i in range(10)]
	for i in lis:
		for j in lis:
			cnt = 0
			swt = 1
			for k in range(n):
				if swt:
					if s[k] == i:
						swt = 0
					else:
						cnt += 1
				elif s[k] == j:
					swt = 1
				else:
					cnt += 1
			if i != j and (n - cnt) % 2 != 0:
				cnt += 1
			ans = min(cnt, ans)
	print(ans)


def find_path(al, bl):
	len_path = 0
	az = bz = 0
	(an, bn) = (len(al), len(bl))
	want_a = True
	ap = bp = -1
	while True:
		if want_a:
			for i in range(az, an):
				if al[i] > bp:
					len_path += 1
					ap = al[i]
					az = i
					want_a = False
					break
			if want_a:
				return len_path
		else:
			for i in range(bz, bn):
				if bl[i] > ap:
					len_path += 1
					bp = bl[i]
					bz = i
					want_a = True
					break
			if not want_a:
				return len_path

def main():
	t = int(input())
	for _ in range(t):
		s = input()
		n = len(s)
		freq = {}
		M = 0
		for i in range(n):
			if s[i] not in freq:
				freq[s[i]] = [i]
			else:
				freq[s[i]].append(i)
		for ca in '0123456789':
			if ca not in freq:
				continue
			for cb in '0123456789':
				if cb not in freq:
					continue
				len_path = find_path(freq[ca], freq[cb])
				if len_path % 2 != 0:
					len_path -= 1
				M = max(M, len_path)
		max_freq = 0
		for val in freq.values():
			max_freq = max(max_freq, len(val))
		print(min(n - 2, n - max_freq, n - M))
main()


for _ in range(int(input())):
	s = input()
	n = len(s)
	a = [0] * 10
	for x in s:
		a[int(x)] += 1
	a = [x for x in a if x]
	a.sort(reverse=True)
	if len(a) == 1:
		print(0)
	else:
		ans = a[0]
		for x in range(10):
			for y in range(10):
				if x != y:
					sm = 0
					b = [str(x), str(y)]
					i = 0
					j = 0
					while j < n:
						if s[j] == b[i]:
							sm += 1
							i ^= 1
						j += 1
					ans = max(ans, 2 * (sm // 2))
		print(n - ans)


for _ in range(int(input())):
	s = input()
	n = len(s)
	pairs = []
	for i in range(10):
		for j in range(10):
			pairs.append(str(i) + str(j))
	maxx = 0
	for i in pairs:
		c = 0
		v = i[0]
		for j in range(n):
			if s[j] == v:
				c += 1
				if v == i[0]:
					v = i[1]
				else:
					v = i[0]
		if v == i[1] and i[0] != i[1]:
			c -= 1
		maxx = max(c, maxx)
	print(n - maxx)


import sys
t = sys.stdin.readline()
while t:
	t = int(t)
	s = input()
	n = len(s)
	ans = n
	for i in range(100):
		if i < 10:
			(a, b) = ('0', str(i))
		else:
			b = str(i % 10)
			a = str(i // 10)
		j = 0
		flag = True
		gd_str = 0
		while j < n:
			if flag:
				while j < n and s[j] != a:
					j += 1
				flag = False
			else:
				while j < n and s[j] != b:
					j += 1
					continue
				if j < n and s[j] == b:
					gd_str += 2
				flag = True
			j += 1
		ans = min(ans, n - gd_str)
	hm = {}
	for i in range(n):
		try:
			hm[s[i]] += 1
		except:
			hm[s[i]] = 1
	print(min(n - max(hm.values()), ans))
	t -= 1


import sys
import math
from collections import Counter
import heapq
try:
	for _ in range(int(input())):
		s = input()
		co = [0] * 10
		(n, ans, m) = (len(s), 0, 0)
		b = 0
		for i in s:
			co[int(i)] += 1
		for i in range(10):
			for j in range(10):
				(ans, b) = (0, 0)
				for k in range(n):
					if b == 0 and i == int(s[k]):
						b = 1
					elif j == int(s[k]) and b == 1:
						b = 0
						ans += 2
				m = max(m, ans)
		for i in range(10):
			m = max(m, co[i])
		print(n - m)
except:
	pass


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
nn = '0123456789'

def gift():
	for _ in range(t):
		s = input()
		ans = len(s)
		for fi in nn:
			for sc in nn:
				state = 0
				now = 0
				for i in s:
					if i == fi and state == 0:
						now += 1
						state = 1
					elif i == sc and state == 1:
						now += 1
						state = 0
				if fi == sc:
					ans = min(ans, len(s) - now)
				else:
					ans = min(ans, len(s) - now + now % 2)
		yield ans
t = int(input())
ans = gift()
print(*ans, sep='\n')


t = int(input())
for _ in range(t):
	s = input()
	counts = {}
	for i in s:
		if i in counts:
			counts[i] += 1
		else:
			counts[i] = 1
	longest = max(counts.values())
	for a1 in '0123456789':
		for a2 in '0123456789':
			length = 0
			found_a1 = False
			for i in s:
				if found_a1:
					if i == a2:
						length += 2
						found_a1 = False
				elif i == a1:
					found_a1 = True
			longest = max(longest, length)
	print(len(s) - longest)


import sys
import math
from functools import reduce
import bisect

def getN():
	return int(input())

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

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

def input():
	return sys.stdin.readline().rstrip()

def index(a, x):
	i = bisect.bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return False
for _ in range(int(input())):
	s = [int(x) for x in input()]
	ans = 0
	for i in range(10):
		for j in range(10):
			t = 0
			k = i
			if i == j:
				continue
			for p in s:
				if p == k:
					if k == j:
						t += 1
						k = i
					else:
						k = j
			ans = max(ans, t)
	nums = [0] * 10
	for i in s:
		nums[i] += 1
	ans *= 2
	ans = max(ans, max(nums))
	print(max(len(s) - ans, 0))


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
from collections import Counter
for case in range(1, itg() + 1):
	s = inp()
	n = len(s)
	ans = n - Counter(s).most_common(1)[0][1]
	for a in range(10):
		a = str(a)
		for b in range(10):
			b = str(b)
			if a == b:
				continue
			count = 0
			next_is_a = True
			for c in s:
				if next_is_a:
					if c == a:
						next_is_a = not next_is_a
						continue
				elif c == b:
					next_is_a = not next_is_a
					continue
				count += 1
			if n - count & 1:
				count += 1
			ans = min(ans, count)
	print(ans)


t = int(input())
while t:
	t -= 1
	s = input()
	if len(list(set(s))) == 1:
		print('0')
	else:
		x = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '11', '12', '13', '14', '15', '16', '17', '18', '19', '22', '23', '24', '25', '26', '27', '28', '29', '33', '34', '35', '36', '37', '38', '39', '44', '45', '46', '47', '48', '49', '55', '56', '57', '58', '59', '66', '67', '68', '69', '77', '78', '79', '88', '89', '99']
		y = [0] * len(x)
		z = [0] * len(x)
		w = [1] * len(x)
		extra = [0] * 10
		ans = [0] * len(x)
		for i in range(len(s)):
			extra[int(s[i])] += 1
			for j in range(len(x)):
				if s[i] == x[j][y[j] % 2]:
					y[j] += 1
					if y[j] % 2 == 0:
						ans[j] += 1
				if s[i] == x[j][w[j] % 2]:
					w[j] += 1
					if w[j] % 2 == 1:
						z[j] += 1
		m = max(max(ans), max(z))
		if 2 * m >= max(extra):
			print(len(s) - 2 * m)
		else:
			print(len(s) - max(extra))


n = int(input())
for i in range(n):
	m = 0
	arr1 = str(input())
	for j in range(0, 10):
		for k in range(0, 10):
			if j < k:
				coun = 0
				y = 0
				for t in range(len(arr1)):
					if coun == 0 and arr1[t] == str(j):
						coun += 1
						y = str(j)
					elif coun == 0 and arr1[t] == str(k):
						coun += 1
						y = str(k)
					elif arr1[t] == str(j) and y == str(k):
						coun += 1
						y = str(j)
					elif arr1[t] == str(k) and y == str(j):
						coun += 1
						y = str(k)
				if coun % 2 == 0 and coun > m:
					m = coun
				elif coun % 2 == 1 and coun - 1 > m:
					m = coun - 1
	for j in range(10):
		if arr1.count(str(j)) > m:
			m = arr1.count(str(j))
	print(len(arr1) - m)


from collections import *
for u in range(int(input())):
	s = input()
	n = len(s)
	c = Counter(s)
	m = n - max(list(c.values()))
	for i in range(10):
		for j in range(10):
			x = 0
			for k in range(n):
				if x % 2 == 0:
					if s[k] == str(i):
						x = x + 1
				elif s[k] == str(j):
					x += 1
			if x % 2 == 1:
				x -= 1
			m = min(m, n - x)
	print(m)


from itertools import count
import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	t = int(input())
	ans_a = [''] * t
	digits = '0123456789'
	for ti in range(t):
		s = input().rstrip()
		ans = 10 ** 9
		for d1 in digits:
			for d2 in digits:
				(x, y) = (d1, d2)
				cnt = 0
				for c in s:
					if c == x:
						(x, y) = (y, x)
					else:
						cnt += 1
				ans = min(ans, cnt + (1 if d1 != d2 and d2 == x else 0))
		ans_a[ti] = str(ans)
	output(*ans_a)
main()


for _ in range(int(input())):
	s = str(input())
	n = len(s)
	m = n

	def check(x, y):
		res = 0
		for k in s:
			if k == x:
				res += 1
				(x, y) = (y, x)
		if res % 2 != 0:
			res -= 1
		return res
	for i in range(10):
		for j in range(10):
			if i == j:
				m = min(n - s.count(str(i)), m)
			else:
				r = check(str(i), str(j))
				m = min(n - r, m)
	print(m)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

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

def ria():
	return list(map(int, sys.stdin.readline().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')
import math, datetime, functools, itertools, operator, bisect, fractions
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	z = []
	for i in range(0, 10):
		for j in range(0, 10):
			if i != j:
				z.append([str(i), str(j)])
	for _ in range(ri()):
		s = rs()
		n = len(s)
		k = Counter(s)
		l = max(k.values())
		ans1 = n - l
		p = 0
		for i in z:
			m = 0
			t = 0
			for j in s:
				if j == i[0] and t == 0:
					t = 1 - t
				elif j == i[1] and t == 1:
					t = 1 - t
					m += 1
			p = max(m, p)
		ans2 = n - 2 * p
		print(min(ans1, ans2))
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


t = int(input())

def find(s, i, j):
	res = 0
	for ch in s:
		if ch == i:
			res += 1
			(i, j) = (j, i)
	if i != j and res % 2 == 1:
		res -= 1
	return res
for _ in range(t):
	s = input()
	correct = 0
	for i in range(10):
		for j in range(10):
			correct = max(correct, find(s, str(i), str(j)))
	print(len(s) - correct)


from functools import reduce
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def inn():
	return int(input())
t = int(input())
while t:
	t -= 1
	a = sarr()
	n = len(a)
	ln = len(set(a))
	if ln == 1:
		print(0)
	elif ln == n:
		print(n - 2)
	else:
		d = defaultdict(int)
		for i in a:
			if i not in d:
				d[i] = 1
			else:
				d[i] += 1
		mx = max(d.values())
		ans = 1000000
		for i in range(10):
			for j in range(10):
				if i != j:
					c = 0
					id = 0
					while id < n:
						while id < n and a[id] != i:
							id += 1
						while id < n and a[id] != j:
							id += 1
						if id == n:
							break
						c += 2
						ans = min(ans, n - c)
		print(min(ans, n - mx))


from sys import stdin, exit, setrecursionlimit
from collections import deque
input = stdin.readline
lmi = lambda : list(map(int, input().split()))
mi = lambda : map(int, input().split())
si = lambda : input().strip('\n')
ssi = lambda : input().strip('\n').split()
for _ in range(int(input())):
	s = list(map(int, list(si())))
	freq = [0 for i in range(10)]
	alt = [[0 for j in range(10)] for i in range(10)]
	vis = [[True for j in range(10)] for i in range(10)]
	for i in s:
		freq[i] += 1
		for j in range(10):
			if j != i:
				vis[i][j] = False
		for j in range(10):
			if not vis[j][i]:
				vis[j][i] = True
				alt[j][i] += 1
	mx = 0
	for i in alt:
		mx = max(max(i), mx)
	freq.sort()
	ans = freq[-1]
	print(len(s) - max(mx * 2, ans))


ans = []
for i in range(10):
	for j in range(10):
		ans.append(str(i) + str(j))
for case in range(int(input())):
	st = input()
	n = len(st)
	ans1 = 0
	for s in ans:
		count = 0
		f = s[0]
		for i in st:
			if i == f:
				count += 1
				if f == s[0]:
					f = s[1]
				else:
					f = s[0]
		if s[0] != s[1] and count % 2 == 1:
			count -= 1
		ans1 = max(ans1, count)
	print(len(st) - ans1)


t = int(input())
for _ in range(t):
	s = input()
	if len(s) == 2:
		print(0)
		continue
	d = {}
	d1 = {}
	for i in range(10):
		for j in range(10):
			if i == j:
				d1[str(i)] = 0
			else:
				d[str(i) + str(j)] = 0
	n = len(s)
	for j in d:
		f = 0
		for i in range(n):
			if s[i] == j[0] and f == 0:
				f = 1
			if s[i] == j[1] and f == 1:
				d[j] += 1
				f = 0
	for j in d1:
		for i in s:
			if i == j:
				d1[j] += 1
	p = max(2 * max(d.values()), max(d1.values()))
	print(n - p)


for _ in range(int(input())):
	s = input()
	n = len(s)
	cnt = [0 for i in range(10)]
	for i in s:
		cnt[int(i)] += 1
	arr = []
	maxa = 0
	for i in range(10):
		for j in range(10):
			tmp = 0
			c = 0
			p = 1
			if i != j:
				for k in s:
					w = int(k)
					if w == i:
						tmp = 1
					if w == j and tmp == 1:
						tmp = 0
						c += 1
				arr.append((i, j))
				maxa = max(c * 2, maxa)
	print(n - max(max(cnt), maxa))


from itertools import product
T = int(input())
for _ in range(T):
	s = input()
	(mn, n) = (len(s), len(s))
	for (a, b) in product(list('0123456789'), list('0123456789')):
		cc = 0
		for ch in s:
			if cc % 2 == 0:
				if ch == a:
					cc += 1
			elif ch == b:
				cc += 1
		if a == b:
			mn = min(mn, n - cc)
		else:
			mn = min(mn, n - cc if cc % 2 == 0 else n - cc + 1)
	print(mn)


t = int(input())

def swap(p):
	b = p[0]
	p[0] = p[1]
	p[1] = b
	return p

def calculate_delets(s, pat):
	or_pat = pat.copy()
	res = 0
	for el in s:
		if el == pat[0]:
			pat = swap(pat)
		else:
			res += 1
	if pat != or_pat:
		res += 1
	return res
for i in range(t):
	s = input()
	l1 = '0123456789'
	l2 = '0123456789'
	m_del = len(s)
	for k1 in l1:
		for k2 in l2:
			pat = [k1, k2]
			m_del = min(calculate_delets(s, pat), m_del)
	print(m_del)


from collections import Counter
from itertools import combinations
for _ in range(int(input())):
	a = list(input())
	n = len(a)
	dic = Counter(a)
	b = list(sorted(dic.items(), key=lambda x: x[1], reverse=True))
	ans = b[0][1]
	if len(b) == 1:
		print(0)
	else:
		for xxx in combinations(dic.keys(), 2):
			(i, j) = (xxx[0], xxx[1])
			if dic[i] + dic[j] < ans:
				continue
			c = ''.join(list(filter(lambda x: x in {i, j}, a)))
			ans = max(ans, 2 * c.count(i + j), 2 * c.count(j + i))
		print(n - 2) if ans == 1 else print(n - ans)


T = int(input())

def isGood(st):
	if len(st) <= 2:
		return True
	even = st[0]
	odd = st[1]
	for (i, c) in enumerate(st):
		if i % 2 == 0:
			if c != even:
				return False
		elif c != odd:
			return False
	if len(st) % 2 != 0 and even != odd:
		return False
	return True
for t in range(T):
	s = input()
	matrix = [[[-1, 0] for i in range(10)] for j in range(10)]
	d = {i: 0 for i in range(10)}
	for c in s:
		cint = int(c)
		d[cint] += 1
		for (i, l) in enumerate(matrix[cint]):
			if i == cint:
				continue
			if l[0] != cint:
				l[0] = cint
				l[1] += 1
		for i in range(10):
			if i == cint:
				continue
			l = matrix[i][cint]
			if l[0] != cint and l[0] != -1:
				l[0] = cint
				l[1] += 1
	max_o = -1
	for i in range(10):
		for j in range(10):
			max_o = max(max_o, matrix[i][j][1])
	if max_o % 2 != 0:
		max_o -= 1
	max_c = max([d[x] for x in range(10)])
	to_sub = 0
	if max_o > max_c:
		to_sub = len(s) - max_o
	else:
		to_sub = len(s) - max_c
	print(min(len(s) - 2, to_sub))


def f(s, n):
	if n % 2 != 0:
		return False
	else:
		p = s[0]
		q = s[1]
		for i in range(0, n, 2):
			if s[i] != p:
				return False
		for i in range(1, n, 2):
			if s[i] != q:
				return False
		return True

def g(s, i, j):
	k = 0
	while int(s[k]) != i:
		k = k + 1
	p = i
	q = j
	l = 1
	for m in range(k + 1, n):
		if int(s[m]) == q:
			l = l + 1
			q = p
			p = int(s[m])
	if l % 2 == 0:
		return l
	else:
		return l - 1
t = int(input())
while t > 0:
	t = t - 1
	s = input()
	n = len(s)
	if f(s, n) == True:
		print(0)
	else:
		d = {}
		m = 0
		for i in s:
			j = int(i)
			if j in d:
				d[j] = d[j] + 1
			else:
				d[j] = 1
			m = max(m, d[j])
		if m == 1:
			print(n - 2)
		else:
			table = [[0 for i in range(10)] for j in range(10)]
			for i in range(10):
				if i not in d:
					for j in range(10):
						table[i][j] = 0
				else:
					for j in range(10):
						if j == i:
							table[i][j] = d[i]
						elif j not in d:
							table[i][j] = 0
						else:
							table[i][j] = g(s, i, j)
			mi = 0
			for i in range(10):
				mi = max(mi, max(table[i]))
			print(n - mi)


from collections import Counter
for _ in range(int(input())):
	s = input()
	c = Counter(s)
	ans = 0
	for i in range(10):
		for j in range(10):
			res = 0
			t = []
			(x, y) = (i, j)
			for k in s:
				if k == str(x):
					res += 1
					t.append(k)
					(x, y) = (y, x)
			if i != j and res & 1:
				res -= 1
			ans = max(ans, res)
	print(len(s) - ans)


import math
T = int(input())
for i in range(T):
	a = input()
	d = False
	f = {}
	q = list('0123456789')
	n = len(a)
	first = [1] * 100
	count = [0] * 100
	for i in a:
		j = int(i)
		for k in range(10):
			if first[j * 10 + k]:
				count[j * 10 + k] += 1
				first[j * 10 + k] ^= 1
			if not first[k * 10 + j]:
				count[10 * k + j] += 1
				first[10 * k + j] ^= 1
	ans = 0
	for i in range(100):
		if i % 10 == i // 10:
			ans = max(ans, count[i] // 2)
		else:
			ans = max(ans, count[i] - count[i] % 2)
	print(n - ans)


import sys, math as mt
import heapq as hp
import math as mt
import collections as cc
I = lambda : list(map(int, input().split()))

def ch(s, a, b):
	aa = 1
	bb = 0
	cnt = 0
	for i in range(len(s)):
		if s[i] == a and aa:
			aa = 0
			bb = 1
		elif s[i] == b and bb:
			bb = 0
			aa = 1
			cnt += 1
	return len(s) - cnt * 2
for tc in range(int(input())):
	s = list(input())
	ans = mt.inf
	n = len(s)
	f = cc.Counter(s)
	for i in f:
		ans = min(ans, n - f[i])
	for i in range(10):
		for j in range(10):
			i = str(i)
			j = str(j)
			ans = min(ans, ch(s, i, j))
	print(ans)


z = '0123456789'
for _ in range(int(input())):
	s = input()
	n = len(s)
	m = 0
	for i in z:
		for j in z:
			c = 0
			for k in range(n):
				if s[k] == i and c % 2 == 0:
					c += 1
				elif s[k] == j and c % 2 == 1:
					c += 1
			if i != j and c % 2 == 1:
				c -= 1
			if c > m:
				m = c
	print(n - m)


t = int(input())
while t > 0:
	num = input()
	ans = 0
	sum = 0
	for i in range(0, 10):
		for j in range(0, 10):
			state = 0
			sum = 0
			c1 = str(i)
			c2 = str(j)
			for k in num:
				if c1 != c2:
					if state == 0 and c1 == k:
						sum += 1
						state = 1
					elif state == 1 and c2 == k:
						sum += 1
						state = 0
				else:
					sum += num.count(c1)
					break
			if state == 1 and sum >= 3:
				sum -= 1
			ans = max(ans, sum)
	print(len(num) - ans)
	t -= 1


from collections import Counter
for _ in range(int(input())):
	s = input()
	n = len(s)
	d = Counter(s)
	maxi = 0
	for i in range(10):
		if d[str(i)] > maxi:
			maxi = d[str(i)]
	mini = min(n - maxi, n - 2)
	for i in range(10):
		for j in range(i + 1, 10):
			ans1 = 0
			ans2 = 0
			for k in range(0, n):
				if s[k] == str(i) and ans1 % 2 == 0:
					ans1 += 1
				elif s[k] == str(j) and ans1 % 2:
					ans1 += 1
				if s[k] == str(j) and ans2 % 2 == 0:
					ans2 += 1
				elif s[k] == str(i) and ans2 % 2:
					ans2 += 1
			if ans1 % 2:
				ans1 -= 1
			if ans2 % 2:
				ans2 -= 1
			mini = min(mini, n - ans1, n - ans2)
	print(mini)


import math

def f(a, b):
	a = str(a)
	b = str(b)
	r = 0
	for e in s:
		if e == a:
			r += 1
			(a, b) = (b, a)
	if r % 2 != 0 and a != b:
		r -= 1
	return r
test = int(input())
for k in range(test):
	s = input()
	(m, a) = (0, 0)
	for i in range(10):
		for j in range(10):
			t = f(i, j)
			a = max(a, t)
	print(abs(a - len(s)))


def searchPattern(s, a, b):
	check = 0
	count = 0
	for letter in s:
		if not check and letter == a:
			count += 1
			check = 1
		elif check and letter == b:
			count += 1
			check = 0
	if a != b and count % 2 == 1:
		count -= 1
	return count

def minDeletes(s):
	maxCount = 0
	sSet = set()
	for c in s:
		sSet.add(c)
	for i in sSet:
		for j in sSet:
			maxCount = max(maxCount, searchPattern(s, i, j))
	return len(s) - maxCount
tests = int(input())
while tests:
	s = input()
	print(minDeletes(s))
	tests -= 1


from collections import Counter
from itertools import combinations
t = int(input())
for test in range(t):
	n = input()
	d = Counter(n)
	digits = list(combinations(set(n), 2))
	ans = sorted(d.items(), key=lambda x: x[1], reverse=True)[0][1]
	for comb in digits:
		f = False
		f1 = True
		c = 0
		for let in n:
			if f1 and let == comb[0]:
				f = True
				f1 = False
				c += 1
			if f and let == comb[1]:
				f = False
				f1 = True
				c += 1
		c -= c % 2
		ans = max(ans, c)
	print(len(n) - ans)


t = int(input())
while t > 0:
	a = list(str(input()))
	d = {}
	d['0'] = []
	d['1'] = []
	d['2'] = []
	d['3'] = []
	d['4'] = []
	d['5'] = []
	d['6'] = []
	d['7'] = []
	d['8'] = []
	d['9'] = []
	for i in range(len(a)):
		d[a[i]].append(i)
	co = 0
	g = d.keys()
	for i in d.keys():
		co = max(co, len(d[i]))
	for i in range(9):
		a1 = d[str(i)]
		if len(a1) == 0:
			continue
		for j in range(i + 1, 10):
			a1 = d[str(i)]
			a2 = d[str(j)]
			if len(a2) == 0:
				continue
			count = 0
			if a1[0] > a2[0]:
				a1d = []
				for k in range(len(a1)):
					a1d.append([a1[k], 1])
				a2d = []
				for k in range(len(a2)):
					a2d.append([a2[k], 0])
				c = list(a1d)
				c.extend(a2d)
				c.sort(key=lambda x: x[0])
				ini = 0
				for k in range(len(a1d) + len(a2d)):
					if ini == c[k][1]:
						count += 1
						if ini == 0:
							ini = 1
						else:
							ini = 0
				if count % 2 != 0:
					count = count - 1
			else:
				a1d = []
				for k in range(len(a1)):
					a1d.append([a1[k], 1])
				a2d = []
				for k in range(len(a2)):
					a2d.append([a2[k], 0])
				c = list(a1d)
				c.extend(a2d)
				c.sort(key=lambda x: x[0])
				ini = 1
				for k in range(len(a1d) + len(a2d)):
					if ini == c[k][1]:
						count += 1
						if ini == 0:
							ini = 1
						else:
							ini = 0
				if count % 2 != 0:
					count = count - 1
			if count > co:
				co = count
	print(len(a) - co)
	t = t - 1


for _ in range(int(input())):
	s = input()
	dp = [[0 for i in range(10)] for j in range(10)]
	mx = 0
	for i in range(10):
		sl = str(i)
		for j in range(10):
			nl = str(j)
			(fi, ei) = (-1, -1)
			used = 0
			for k in range(len(s)):
				if i == j and s[k] == sl:
					dp[i][i] += 1
					continue
				elif i == j:
					continue
				else:
					if s[k] == sl:
						fi = k
						used = 0
					elif s[k] == nl:
						ei = k
					if not used and ei > fi and (fi >= 0):
						dp[i][j] += 1
						used = 1
			if i != j:
				mx = max(mx, dp[i][j])
	mx = max(mx * 2, max((dp[i][i] for i in range(10))))
	print(len(s) - mx)


import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

def solve(arr):
	console('----- solving ------')
	c = Counter(arr)
	res = max(c.values())
	for a in range(10):
		a = str(a)
		for b in range(10):
			b = str(b)
			if a == b:
				continue
			sets = 0
			expect_b = False
			for x in arr:
				if expect_b and x == b:
					expect_b = False
					sets += 1
				elif x == a:
					expect_b = True
			res = max(res, sets * 2)
	return len(arr) - res

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	strr = input()
	res = solve(strr)
	print(res)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
from collections import Counter
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007

def make(a, b):
	i = j = 0
	arr = []
	while i < len(a) and j < len(b):
		if a[i] < b[j]:
			if not len(arr) or arr[-1] != 'a':
				arr.append('a')
			i += 1
		else:
			if not len(arr) or arr[-1] != 'b':
				arr.append('b')
			j += 1
	if i < len(a) and arr[-1] != 'a':
		arr.append('a')
	if j < len(b) and arr[-1] != 'b':
		arr.append('b')
	if len(arr) % 2 != 0:
		arr.pop()
	return len(arr)
tc = ii1()
for _ in range(tc):
	s = is1()
	d = Counter(s)
	res = 0
	for i in d:
		res = max(res, d[i])
	res = min(len(s) - 2, len(s) - res)
	d = {}
	for i in range(len(s)):
		d.setdefault(int(s[i]), []).append(i)
	for i in d:
		for j in d:
			if i != j:
				t = len(s) - make(d[i], d[j])
				res = min(res, t)
	print(res)


def check(a, b):
	ok = False
	cnt = 0
	for i in range(len(u)):
		if ok and u[i] == a:
			cnt += 1
			ok = False
		elif not ok and u[i] == b:
			cnt += 1
			ok = True
	if a == b:
		return cnt
	return cnt - cnt % 2
ans = []
for stp in range(int(input())):
	u = list(map(int, list(input())))
	ansi = 0
	for i in range(10):
		for j in range(10):
			ansi = max(ansi, check(i, j))
	ans.append(len(u) - ansi)
print('\n'.join(map(str, ans)))


for _ in range(int(input())):
	s = input()
	ans = 0
	for d1 in '1234567890':
		for d2 in '1234567890':
			d11 = d1
			d21 = d2
			cur_ans = 0
			for c in s:
				if c == d11:
					cur_ans += 1
					(d11, d21) = (d21, d11)
			if d1 != d2:
				cur_ans = cur_ans // 2 * 2
			ans = max(ans, cur_ans)
	print(len(s) - ans)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

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

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

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 swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	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 phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(councils, a, k):
	summ = 0
	for x in a:
		summ += min(x, councils)
	return summ // councils >= k
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	s = input().rstrip()
	d = {}
	n = len(s)
	for x in s:
		a = d.get(x, 0)
		d[x] = a + 1
	val = list(d.values())
	ans = n - max(val)
	nums = '0123456789'
	for i in nums:
		for j in nums:
			f = True
			c = 0
			for x in s:
				if x == i and f:
					c += 1
					f = False
				elif x == j and (not f):
					c += 1
					f = True
			if c % 2 == 1:
				c -= 1
			ans = min(ans, len(s) - c)
	print(ans)
for _ in range(int(input())):
	solve()


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')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
from types import GeneratorType

def bootstrap(func, stack=[]):

	def wrapped_function(*args, **kwargs):
		if stack:
			return func(*args, **kwargs)
		else:
			call = func(*args, **kwargs)
			while True:
				if type(call) is GeneratorType:
					stack.append(call)
					call = next(call)
				else:
					stack.pop()
					if not stack:
						break
					call = stack[-1].send(call)
			return call
	return wrapped_function

def solve(s, fir, sec):
	flag = True
	cnt = 0
	(fir, sec) = (chr(ord('0') + fir), chr(ord('0') + sec))
	for i in range(len(s)):
		if flag:
			if s[i] == fir:
				cnt += 1
				flag = not flag
		elif s[i] == sec:
			cnt += 1
			flag = not flag
	if flag:
		return cnt
	elif fir == sec:
		return cnt
	else:
		return cnt - 1
for _ in range(int(ri())):
	s = ri()
	ans = len(s) - 2
	for i in range(0, 10):
		for j in range(0, 10):
			ret = solve(s, i, j)
			ans = min(ans, len(s) - ret)
	print(ans)


import math
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
	s = input()[:-1]
	answer = math.inf
	for n1 in range(10):
		sn1 = str(n1)
		for n2 in range(10):
			sn2 = str(n2)
			lookn1 = True
			current = 0
			for c in s:
				if c == sn1 and lookn1:
					lookn1 = False
					current += 1
				elif c == sn2 and (not lookn1):
					lookn1 = True
					current += 1
			if current % 2 and n1 != n2:
				current -= 1
			answer = min(answer, len(s) - current)
	print(answer)


for __ in range(int(input())):
	ar = list(map(int, input()))
	kek = [[] for i in range(10)]
	i = 0
	for elem in ar:
		kek[elem].append(i)
		i += 1
	ans = 0
	for i in range(10):
		z = 0
		fifi = [0] * 10
		while z < len(kek[i]) - 1:
			lol = set()
			for j in range(kek[i][z] + 1, kek[i][z + 1]):
				lol.add(ar[j])
			for elem in lol:
				fifi[elem] += 1
			z += 1
		for j in range(10):
			flag = 0
			if kek[i]:
				for z in range(kek[i][0]):
					if ar[z] == j:
						flag = 2
			ans = max(ans, fifi[j] * 2 + flag, len(kek[i]))
	print(len(ar) - ans)


for qwerty in range(int(input())):
	s = input()
	ans = 10 ** 8
	for i in range(10):
		t = 0
		for j in s:
			if int(j) != i:
				t += 1
		ans = min(ans, t)
	for a in range(10):
		for b in range(10):
			q = 0
			t = 0
			for j in s:
				if int(j) == a and q == 0 or (int(j) == b and q == 1):
					q = (q + 1) % 2
				else:
					t += 1
			t += (len(s) - t) % 2
			ans = min(ans, t)
	print(ans)


from collections import Counter
n = int(input())
for _ in range(n):
	s = input()
	c = Counter(s).most_common()
	a = c[0][1]
	m = c[0][1]
	arr = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
	for i in range(9):
		arr.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
	for i in s:
		p = int(i)
		for j in range(10):
			if p > j:
				if arr[j][p] == 1 or (arr[j][p] == 0 and arr[p][j] == 0):
					arr[j][p] = 0
					arr[p][j] += 1
					if arr[p][j] > m:
						m = arr[p][j]
			elif p < j:
				if arr[p][j] == 0:
					arr[p][j] = 1
					arr[j][p] += 1
					if arr[j][p] > m:
						m = arr[j][p]
	if m % 2 == 1:
		m -= 1
	if a > m:
		print(len(s) - a)
	else:
		print(len(s) - m)


t = int(input())
while t:
	t -= 1
	s = input()
	if len(list(set(s))) == 1:
		print('0')
	else:
		x = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']
		l = len(x)
		y = [0] * l
		extra = [0] * 10
		ans = [0] * l
		for i in range(len(s)):
			extra[int(s[i])] += 1
			for j in range(l):
				if s[i] == x[j][y[j] % 2]:
					y[j] += 1
					if y[j] % 2 == 0:
						ans[j] += 1
		print(len(s) - max(2 * max(ans), max(extra)))


for _ in range(int(input())):
	s = list(input())
	n = len(s)
	ss = '0123456789'
	d = []
	dd = []
	for i in ss:
		c = 0
		for j in s:
			if i == j:
				c += 1
		dd.append(c)
	for i in ss:
		for j in ss:
			c = 1
			cou = 0
			for k in range(n):
				if c != 0 and s[k] == i:
					c ^= 1
				elif c == 0 and s[k] == j:
					c ^= 1
					cou += 1
			d.append(cou)
	ans = max(max(dd), 2 * max(d))
	print(n - ans)


t = int(input())
for x in range(t):
	testcase = str(input())
	K = len(testcase)
	best = K - 2
	for i in range(10):
		for j in range(10):
			digits = (i, j)
			nextch = i
			count = 0
			for ch in testcase:
				if int(ch) != nextch:
					count += 1
				elif nextch == i:
					nextch = j
				elif nextch == j:
					nextch = i
			if nextch == j and i != j:
				count += 1
			best = min(best, count)
	print(best)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	ss = list(map(int, list(input())))
	best = 0
	for i in range(10):
		for j in range(10):
			next = i
			count = 0
			for s in ss:
				if s == next:
					next = i if next == j else j
					count += 1
			if next == j and i != j:
				count -= 1
			best = max(best, count)
	print(len(ss) - best)

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


for _ in range(int(input())):
	s = input()
	l = len(s)
	d = {}
	for i in s:
		d[i] = d.get(i, 0) + 1
	m = max(d.values())
	for i in range(10):
		for j in range(10):
			c = 0
			for k in range(l):
				if c % 2 == 0:
					if s[k] == str(i):
						c = c + 1
				elif s[k] == str(j):
					c = c + 1
			if c % 2:
				c = c - 1
			m = max(m, c)
	print(l - m)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	s = list(inp())
	n = len(s)
	for i in range(n):
		s[i] = int(s[i])
	cnt = {}
	for i in range(10):
		cnt[i] = 0
	for i in range(n):
		cnt[s[i]] += 1
	ans = 10 ** 9
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			if cnt[i] > 0 and cnt[j] > 0:
				new = []
				for ii in range(n):
					if s[ii] == i or s[ii] == j:
						new.append(s[ii])
				a1 = 0
				a2 = 0
				for ii in range(len(new)):
					if a1 % 2 == 0:
						if new[ii] == i:
							a1 += 1
					elif new[ii] == j:
						a1 += 1
				for ii in range(len(new)):
					if a2 % 2 == 0:
						if new[ii] == j:
							a2 += 1
					elif new[ii] == i:
						a2 += 1
				if a1 % 2 == 1:
					a1 -= 1
				if a2 % 2 == 1:
					a2 -= 1
				ans = min(ans, n - a1, n - a2)
	for i in range(10):
		ans = min(ans, n - cnt[i])
	print(ans)
testcase(int(inp()))


def solve_util(s, x, y):
	res = 0
	for c in s:
		if c == x:
			res += 1
			(x, y) = (y, x)
	if x != y and res % 2 == 1:
		return res - 1
	return res

def solve(s):
	ans = 0
	a = [str(i) for i in range(10)]
	for x in a:
		for y in a:
			ans = max(ans, solve_util(s, x, y))
	return ans

def read():
	t = int(input())
	for i in range(t):
		s = input()
		ans = solve(s)
		print(len(s) - ans)
read()


def fun(S, s):
	N = len(S)
	i = 0
	flip = 1
	cun = 0
	while i < N:
		if flip:
			if S[i] == s[0]:
				i += 1
				flip = 1 - flip
				continue
		elif S[i] == s[1]:
			flip = 1 - flip
			cun += 1
			i += 1
			continue
		i += 1
	return cun
for _ in range(int(input())):
	S = input()
	N = len(S)
	if N <= 2:
		print(0)
		continue
	Always = N - 2
	Single = 0
	for i in range(10):
		s = str(i)
		count = S.count(s)
		if count != -1:
			Single = max(Single, count)
	Double = 0
	for i in range(0, 100):
		if i < 10:
			s = '0' + str(i)
		else:
			s = str(i)
		count = fun(S, s)
		Double = max(Double, count)
	X = min(Always, N - Single, N - 2 * Double)
	print(X)


for _ in range(int(input())):
	s = input()
	ans = 0
	dic = [0] * 10
	mx = 0
	for i in s:
		dic[int(i)] += 1
		if mx < dic[int(i)]:
			mx = dic[int(i)]
	ans = len(s) - mx
	s1 = '0'
	s2 = '0'
	flag = 0
	while int(s1) <= 9 and int(s2) <= 9:
		for i in s:
			if flag & 1 and s2 == i or (flag % 2 == 0 and s1 == i):
				flag += 1
		if flag % 2 == 0:
			ans = min(len(s) - flag, ans)
		v = int(s1 + s2) + 1
		s1 = str(v // 10)
		s2 = str(v % 10)
		flag = 0
	print(ans)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
t = ip()
for _ in range(t):
	s = ips()
	n = len(s)
	ideal = '0123456789'
	dic = Counter(s)
	ans = -1
	for i in dic:
		ans = max(dic[i], ans)
	for i in range(len(ideal)):
		for j in range(len(ideal)):
			if i == j:
				pass
			else:
				a = ideal[i]
				b = ideal[j]
				flag = True
				ct = 0
				stack = []
				for ii in s:
					if len(stack) == 0:
						if ii == a:
							stack.append(ii)
					elif ii == b:
						stack.pop()
						ct += 1
				ans = max(ans, 2 * ct)
	print(n - ans)


from collections import defaultdict as dc
for _ in range(int(input())):
	s = input()
	n = len(s)
	p = 0
	for i in range(10):
		for j in range(10):
			f = 0
			q = 0
			if i != j:
				for k in range(n):
					if f == 0:
						if s[k] == chr(48 + i):
							f = 1
					elif f == 1:
						if s[k] == chr(48 + j):
							f = 0
							q += 1
				p = max(p, 2 * q)
			elif i == j:
				for k in range(n):
					if s[k] == chr(48 + i):
						q += 1
				p = max(p, q)
	if n == 1:
		print(0)
	else:
		print(n - p)


import sys
from collections import defaultdict
p = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(int(input())):
	s = list(input())
	l = list(set(s))
	d = defaultdict(int)
	for i in s:
		d[i] += 1
	m = -1
	for i in l:
		for j in l:
			if i != j:
				c = 0
				f = 0
				for x in s:
					if f == 0 and x == i or (f == 1 and x == j):
						c += 1
						f = 1 - f
				m = max(m, c // 2 * 2)
	m = max(m, max(d.values()))
	print(len(s) - m)


for _ in range(int(input())):
	s = str(input())
	l = list(s)
	if len(list(set(l))) == 1:
		print(0)
	else:
		l1 = [0] * 10
		l2 = [-1] * 10
		for i in range(len(s)):
			l1[int(s[i])] += 1
			l2[int(s[i])] = 1
		ans = min(len(s) - max(l1), len(s) - 2)
		l3 = []
		for i in range(10):
			if l2[i] == 1:
				l3.append(i)
		mv = 0
		for i in range(len(l3)):
			for j in range(len(l3)):
				f = 0
				x1 = 0
				y1 = 0
				for k in range(len(s)):
					if f == 0 and int(s[k]) == l3[i]:
						f = 1
						x1 += 1
					elif f == 1 and int(s[k]) == l3[j]:
						f = 0
						y1 += 1
				mv = max(mv, 2 * min(x1, y1))
		print(min(ans, len(s) - mv))


t = int(input())
for _ in range(t):
	s = list(map(int, input()))
	best = 0
	for d in range(10):
		c = s.count(d)
		best = max(best, c)
	for d1 in range(10):
		for d2 in range(10):
			if d1 == d2:
				continue
			find1 = True
			count = 0
			for d in s:
				if find1 and d == d1:
					count += 1
					find1 = not find1
				elif not find1 and d == d2:
					count += 1
					find1 = not find1
			best = max(best, count - count % 2)
	print(len(s) - best)


from itertools import product
for _ in range(int(input())):
	s = input()
	res = min(2, len(s))
	for (c1, c2) in product('0123456789', repeat=2):
		cnt = 0
		idx = 0
		for c in s:
			if c == (c1 if idx == 0 else c2):
				cnt += 1
				idx = 1 - idx
		res = max(res, cnt // 2 * 2 if c1 != c2 else cnt)
	print(len(s) - res)


w = int(input())
for _ in range(w):
	A = list(map(int, list(input())))
	MAX = 0
	for i in range(10):
		for j in range(10):
			cur = i
			l = 0
			for k in A:
				if k == cur:
					if cur == i:
						cur = j
					else:
						cur = i
					l += 1
			MAX = max(MAX, l)
	if MAX % 2 == 0:
		print(len(A) - MAX)
	else:
		dic = [0] * 10
		for i in A:
			dic[i] += 1
		if MAX == max(dic):
			print(len(A) - MAX)
		else:
			print(len(A) - MAX + 1)


from collections import Counter
t = int(input())
for _ in range(t):
	ar = list(map(int, list(input())))
	n = len(ar)
	cntr = Counter(ar)
	Set = list(cntr.keys())
	if len(cntr) == 1:
		print(0)
	elif len(cntr) == n:
		print(n - 2)
	else:
		checkAr = [[-1 for i in range(10)] for j in range(10)]
		countAr = [[0 for i in range(10)] for j in range(10)]
		mx = max(cntr.values())
		for idx in range(n):
			if idx > 0 and ar[idx] == ar[idx - 1]:
				continue
			char = ar[idx]
			for i in Set:
				if char > i:
					if checkAr[char][i] != char:
						checkAr[char][i] = char
						countAr[char][i] += 1
						mx = max(countAr[char][i], mx)
				elif checkAr[i][char] != char:
					checkAr[i][char] = char
					countAr[i][char] += 1
					mx = max(countAr[i][char], mx)
		if mx != max(cntr.values()) and mx % 2 == 1:
			mx = mx - 1
		output = n - mx
		print(output)


def main():
	return '\n'.join(map(str, (nCharactersToEraseFrom(input()) for _ in range(int(input())))))

def nCharactersToEraseFrom(string):
	repetition = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0}
	for letter in string:
		repetition[letter] += 1
	longestLength1 = max(repetition.values())
	letters = tuple(set(string))
	if len(letters) > 1:
		longestLength2 = max((goodStringLengthFrom(string, {letters[i], letters[j]}) for i in range(len(letters) - 1) for j in range(i + 1, len(letters))))
	else:
		longestLength2 = 0
	if longestLength1 >= longestLength2:
		return len(string) - longestLength1
	return len(string) - (longestLength2 - 1 if longestLength2 % 2 else longestLength2)

def goodStringLengthFrom(string, pairOfLetters):
	currLetter = [0]
	return sum((isElement(l, pairOfLetters, currLetter) for l in string))

def isElement(letter, letters, currLetter):
	if letter in letters and letter != currLetter[0]:
		currLetter[0] = letter
		return 1
	return 0
print(main())


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	a = input().strip()
	n = len(a)
	m = n
	for i in range(0, 10):
		for j in range(0, 10):
			if i == j:
				continue
			c = 0
			p = [str(i), str(j)]
			k = 0
			t = 0
			while k < n:
				if a[k] == p[t]:
					t += 1
				if t == 2:
					t = 0
					c += 2
				k += 1
			m = min(m, n - c)
	c = Counter(a)
	for i in c:
		m = min(m, n - c[i])
	print(m)
for _ in range(I()):
	solve()


def ip():
	return int(input())

def sip():
	return input()

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

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

def matip(n, m):
	lst = []
	for i in range(n):
		arr = lip()
		lst.append(arr)
	return lst
t = ip()
while t:
	t -= 1
	s = sip()
	n = len(s)
	maxx = 0
	maxxs = 0
	for i in range(0, 10):
		maxxs = max(maxxs, s.count(str(i)))
	for i in range(0, 100):
		cnt = 0
		y = str(i)
		if len(y) == 1:
			y = '0' + y
		f = 0
		for j in range(n):
			if s[j] == y[0]:
				f = 1
			elif s[j] == y[1] and f == 1:
				cnt += 1
				f = 0
		maxx = max(maxx, cnt)
	print(min(len(s) - 2 * maxx, len(s) - maxxs))


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

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

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write('\n'.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from fractions import Fraction
INF = float('inf')
mod = int(1000000000.0) + 7
for t in range(int(data())):
	s = data()
	l = [0] * 10
	for i in range(len(s)):
		l[int(s[i])] += 1
	ans = max(max(l), 2)
	for i in range(10):
		a = str(i)
		l = [0] * 10
		d = [0] * 10
		for k in range(len(s)):
			if s[k] == a:
				break
		for j in range(k + 1, len(s)):
			if s[j] == a:
				for i in range(10):
					l[i] += d[i]
				d = [0] * 10
			else:
				d[int(s[j])] = 1
		for i in range(10):
			l[i] += d[i]
		ans = max(ans, 2 * max(l))
	out(len(s) - ans)


import sys
input = sys.stdin.readline
from collections import Counter
t = int(input())
for tests in range(t):
	S = input().strip()
	LEN = len(S)
	ANS = LEN
	C = Counter(S)
	for v in C.values():
		ANS = min(ANS, LEN - v)
	for i in '0123456789':
		for j in '0123456789':
			if i == j:
				continue
			count = 0
			flag = 0
			for s in S:
				if flag == 0 and s == i:
					count += 1
					flag = 1
				elif flag == 1 and s == j:
					count += 1
					flag = 0
			ANS = min(ANS, LEN - count // 2 * 2)
	print(ANS)


from sys import stdin, stdout
from collections import defaultdict as dd
from bisect import bisect_left as bl
input = stdin.readline
for _ in range(int(input())):
	a = list(input())
	a.pop()
	d = dd(list)
	for i in range(len(a)):
		d[int(a[i])].append(i)
	ans = 0
	for i in d.keys():
		ans = max(ans, len(d[i]))
	x = list(d.keys())
	for i in range(len(x)):
		for j in range(len(x)):
			if i != j:
				r = 0
				s = bl(d[x[j]], d[x[i]][r])
				k = 0
				while r < len(d[x[i]]) and s < len(d[x[j]]):
					k += 2
					r = bl(d[x[i]], d[x[j]][s])
					if r < len(d[x[i]]):
						s = bl(d[x[j]], d[x[i]][r])
				ans = max(ans, k)
	stdout.write(str(len(a) - ans) + '\n')


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	best = 0
	for i in range(0, 10):
		a = chr(48 + i)
		for j in range(0, 10):
			b = chr(48 + j)
			curlen = 0
			cur = 0
			for c in s:
				if cur == 0:
					if c == a:
						curlen += 1
						cur ^= 1
				elif c == b:
					curlen += 1
					cur ^= 1
			best = max(best, curlen if a == b else curlen - curlen % 2)
	print(n - best)


for _ in range(int(input())):
	s = input()
	x = [0] * 10
	for i in s:
		x[int(i)] += 1
	mmm = max(x)
	lll = [i for i in range(10) if x[i] > mmm / 2]
	pat = []
	for i in lll:
		for j in lll:
			if i != j:
				pat.append((i, j))
	if len(pat) < 1:
		print(len(s) - mmm)
		continue
	sol = [0] * len(pat)
	for i in range(len(s)):
		for j in range(len(pat)):
			if int(s[i]) == pat[j][sol[j] % 2]:
				sol[j] += 1
	print(len(s) - max(max(sol) // 2 * 2, mmm))


t = int(input())
for i in range(t):
	st = input()
	lis = []
	for j in range(len(st)):
		lis.append(st[j])
	uni = set()
	stack = []
	cnt = 0
	combination = []
	for j in range(10):
		for k in range(10):
			st22 = str(j) + str(k)
			combination.append(st22)
	ans = 0
	for k in combination:
		res = 0
		for kl in range(len(st)):
			if st[kl] == k[0] and res % 2 == 0:
				res += 1
			elif st[kl] == k[1] and res % 2 == 1:
				res += 1
		if k[0] != k[1] and res % 2 == 1:
			res -= 1
		ans = max(ans, res)
	print(len(st) - ans)


from collections import Counter
t = int(input())
for _ in range(t):
	s = input()
	ans = len(s) - max(Counter(s).values())
	for l in range(10):
		for r in range(10):
			if l == r:
				continue
			now = 'r'
			cnt = 0
			for c in s:
				if now == 'r' and c == str(l):
					now = 'l'
				elif now == 'l' and c == str(r):
					now = 'r'
					cnt += 1
			ans = min(ans, len(s) - 2 * cnt)
	print(ans)


def fun(o, p):
	c = c2 = c1 = c0 = 0
	for i in range(n):
		if s[i] == p:
			c1 = 1
		if c1 == 1:
			if s[i] == o:
				c += 1
				c1 = 0
	for i in range(n):
		if s[i] == o:
			c2 = 1
		if c2 == 1:
			if s[i] == p:
				c0 += 1
				c2 = 0
	return max(c, c0)
for _ in range(int(input())):
	s = input()
	l = []
	for i in range(10):
		l.append([i, 0])
	for i in s:
		l[int(i)][1] += 1
	l.sort(key=lambda x: x[1], reverse=True)
	k = l[1][1]
	n = len(s)
	su = 0
	for i in range(10):
		for j in range(i + 1, 10):
			su = max(su, fun(str(l[i][0]), str(l[j][0])))
	if l[1][1] == 0:
		print(0)
	else:
		print(min(n - 2 * su, n - l[0][1]))


from collections import Counter
for _ in range(int(input())):
	s = list(map(int, input()))
	n = len(s)
	best = n
	for fc in range(10):
		for sc in range(10):
			dele = 0
			i = 0
			sec = False
			while i < n:
				v = s[i]
				if not sec and v == fc:
					sec = True
				elif sec and v == sc:
					sec = False
				else:
					dele += 1
				i += 1
			if sec and fc != sc:
				dele += 1
			best = min(best, dele)
	print(best)


import sys
input = sys.stdin.readline

def solve(char):
	ind = 0
	cnt = 0
	for c in s:
		if c == char[ind]:
			cnt += 1
			ind ^= 1
	if char[0] != char[1]:
		cnt = cnt // 2 * 2
	return len(s) - cnt
t = int(input())
for _ in range(t):
	s = input()[:-1]
	ans = len(s)
	for i in range(0, 10):
		for j in range(0, 10):
			char = (str(i), str(j))
			ans = min(ans, solve(char))
	print(ans)


t = int(input())
for _ in range(t):
	s = list(str(input()))
	d = [0] * 10
	for i in range(len(s)):
		d[int(s[i])] += 1
	max_len = max(d)
	for a in range(0, 10):
		for b in range(0, 10):
			now_len = 0
			p = a
			for i in range(len(s)):
				if int(s[i]) == p:
					now_len += 1
					if p == a:
						p = b
					else:
						p = a
			max_len = max(max_len, now_len - now_len % 2)
	print(len(s) - max_len)


def alt(a, i, j):
	c = 0
	now = i
	for k in range(len(a)):
		if a[k] == i and now == i:
			now = j
		elif a[k] == j and now == j:
			now = i
			c += 1
	return c * 2

def main():
	for _ in range(int(input())):
		a = list(input())
		x = [i for i in range(10)]
		m = 0
		for i in range(10):
			for j in range(10):
				if i != j:
					m = max(m, alt(a, str(i), str(j)))
				else:
					m = max(m, a.count(str(i)))
		print(len(a) - m)
main()


digits = list('0123456789')

def f(s):
	p = 0
	n = len(s)
	for i in digits:
		for j in digits:
			xx = i
			m = 0
			last = 0
			for mm in range(n):
				if s[mm] == xx:
					last = mm
					m += 1
					if xx == i:
						xx = j
					else:
						xx = i
			if s[last] == i and i != j:
				m -= 1
			p = max(m, p)
	return len(s) - p
n = int(input())
for i in range(n):
	x = input()
	print(f(x))


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
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='z', func=lambda a, b: min(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 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

def check(s, d):
	n = len(s)
	m = 0
	for i in range(10):
		m = max(m, d[i])
	for i in range(10):
		for j in range(10):
			sw = 0
			if i == j:
				continue
			t = 1
			for k1 in range(n):
				if int(s[k1]) == i and t == 1:
					sw += 1
					t = 0
				elif int(s[k1]) == j and t == 0:
					sw += 1
					t = 1
			if sw % 2 == 0:
				m = max(m, sw)
	return m
for ik in range(int(input())):
	s = input()
	d = defaultdict(int)
	for i in s:
		d[int(i)] += 1
	print(len(s) - check(s, d))


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')
from collections import Counter
import heapq
from collections import Counter
for _ in range(int(input())):
	s = input()
	le = len(s)
	ans = le - 1
	d = [0] * 10
	for i in s:
		d[int(i)] += 1
	for i in range(10):
		ans = min(ans, le - d[i])
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			f = 0
			cnt = 0
			for ch in s:
				if f == 0 and ch == str(i):
					f = 1
					cnt += 1
				elif f == 1 and ch == str(j):
					f = 0
					cnt += 1
			cnt = cnt // 2 * 2
			ans = min(ans, le - cnt)
	print(ans)


import sys
import math
mod = 10 ** 9 + 7
inf = float('inf')

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

def LI():
	return list(map(int, sys.stdin.readline().split()))
t = I()
for _ in range(t):
	s = input()
	n = len(s)
	ans = n
	for i in range(10):
		for j in range(10):
			if i == j:
				ans = min(ans, n - s.count(str(i)))
				continue
			flag1 = False
			flag2 = True
			cnt = 0
			for k in range(n):
				if s[k] == str(i) and (not flag1) and flag2:
					flag1 = True
					cnt += 1
					flag2 = False
				elif s[k] == str(j) and (not flag2) and flag1:
					flag2 = True
					cnt += 1
					flag1 = False
			if cnt % 2:
				ans = min(ans, n - (cnt - 1))
			else:
				ans = min(ans, n - cnt)
	print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	s = stdin.readline()
	n = len(s)
	if len(s) > 2:
		m = 2
	else:
		print(0)
		continue
	for i in range(10):
		m = max(m, s.count(str(i)))
	s1 = s[0]
	for i in s[1:n]:
		if i != s1[-1]:
			s1 += i
	s = s1
	for i in '0123456789':
		if i in s:
			j = s.index(i)
			d1 = {}
			d2 = {}
			for c in '0123456789':
				d1[c] = 0
			temp = s[j + 1:]
			for k in temp:
				if k != i:
					d2[k] = 1
				else:
					for c in d2.keys():
						d1[c] += 1
					d2 = {}
			m = max(m, max(d1.values()) * 2)
			j = n - s[::-1].index(i)
			d1 = {}
			d2 = {}
			for c in '0123456789':
				d1[c] = 0
			temp = s[:j]
			for k in temp:
				if k != i:
					d2[k] = 1
				else:
					for c in d2.keys():
						d1[c] += 1
					d2 = {}
			m = max(m, max(d1.values()) * 2)
	print(n - m - 1)


t = int(input())
for _ in range(t):
	s = str(input())
	if s[-1] + s[:len(s) - 1] == s[1:] + s[0]:
		print(0)
		continue
	s = [x for x in s]
	a = '0123456789'
	d = {x + y: [False, 0] for x in a for y in a}
	for (i, x) in enumerate(s):
		for y in a:
			z = x + y
			if not d[z][0]:
				d[z][0] = True
				d[z][1] += 1
			z = y + x
			if d[z][0]:
				d[z][0] = False
				d[z][1] += 1
	ans = 0
	for x in a:
		d[x + x][1] //= 2
	for x in d.keys():
		if x[0] == x[1]:
			ans = max(ans, d[x][1])
		else:
			ans = max(ans, int(d[x][1] // 2) * 2)
	print(int(len(s) - ans))


import collections

def solve(s, i, j):
	b = True
	u = 0
	for x in s:
		if b and x == i:
			b = False
			u += 1
		elif not b and x == j:
			b = True
			u += 1
	if not b:
		u -= 1
	return u
for _ in range(int(input())):
	s = list(map(int, input()))
	u = collections.Counter(s).most_common(1)[0][1]
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			u = max(u, solve(s, i, j))
	print(len(s) - u)


n = int(input())
for i in range(n):
	s = input()
	l = len(s)
	d = dict()
	for i in '0123456789':
		d[i] = 0
	for i in s:
		d[i] = d[i] + 1
	d = sorted(d.items(), key=lambda x: x[1], reverse=True)
	maxi = d[0][1]
	arr = d
	for i in range(len(arr)):
		for j in range(len(arr)):
			if i == j:
				continue
			else:
				e = arr[i][0]
				f = arr[j][0]
				slag = -1
				sount = 0
				for q in s:
					if q == e:
						slag = 0
					if q == f and slag == 0:
						sount = sount + 1
						slag = 1
				if sount * 2 >= maxi:
					maxi = sount * 2
	print(l - maxi)


def solve():
	s = list(map(int, input()))
	n = len(s)
	c = [0] * 10
	for i in s:
		c[i] += 1
	ans = max(c)
	for u in range(10):
		for v in range(10):
			if u == v:
				continue
			res = [0, 0]
			for i in range(n):
				if s[i] == u:
					res[0] = max(res[0], res[1] + 1)
				elif s[i] == v:
					res[1] = max(res[1], res[0] + 1)
			ans = max(ans, max(res) - max(res) % 2)
	print(n - ans)
t = int(input())
for _ in range(t):
	solve()


from collections import Counter
from collections import OrderedDict

def SOCountR(mylist):
	return OrderedDict(sorted(Counter(mylist).items(), reverse=True))

def SOCount(mylist):
	return OrderedDict(sorted(Counter(mylist).items()))

def freq_count(mylist):
	return Counter(mylist)
t = int(input())
for _ in range(t):
	arr = list(input())
	arr = [int(x) for x in arr]
	fre = freq_count(arr)
	ans = max(fre.values())
	gans = 0
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			lans = 0
			check = i
			for k in range(len(arr)):
				if arr[k] == check:
					lans += 1
					if check == i:
						check = j
					else:
						check = i
			gans = max(gans, lans)
	gans = gans - 1 if gans % 2 != 0 else gans
	mans = max(gans, ans)
	print(len(arr) - mans)


from sys import stdin
input = stdin.readline

def answer():
	count = [0] * 10
	for i in s:
		count[int(i)] += 1
	ans = n - max(count)
	for v1 in range(10):
		for v2 in range(10):
			(x, take) = (0, 0)
			for i in range(n):
				if take == 0:
					if int(s[i]) == v1:
						x += 1
						take = 1
				elif int(s[i]) == v2:
					x += 1
					take = 0
			x -= take
			ans = min(ans, n - x)
	return ans
for T in range(int(input())):
	s = input().strip()
	n = len(s)
	print(answer())


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')
t = int(input())
for i in range(t):
	s = input()
	b = []
	for j in s:
		b.append(int(j))
	n = len(b)
	ans = 2
	for i in range(0, 10):
		for j in range(0, 10):
			l = 0
			curr = 0
			while curr < n:
				if l % 2 == 0:
					if b[curr] == i:
						l += 1
				elif b[curr] == j:
					l += 1
				curr += 1
			if l % 2 != 0 and i != j:
				l -= 1
			ans = max(ans, l)
	print(n - ans)


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	s = ii()
	slov = [0] * 10
	data = [0] * 10
	for i in range(len(s)):
		data[int(s[i])] += 1
	ans = max(data)
	for i in range(10):
		slov[i] = 1
	for i in range(len(s)):
		if slov[int(s[i])] == 1:
			slov[int(s[i])] = 0
			data = [0] * 10
			data[int(s[i])] = 1
			data1 = [1] * 10
			for j in range(i, len(s)):
				if s[j] != s[i] and data1[int(s[j])] == 1:
					data1[int(s[j])] = 0
					data[int(s[j])] += 1
				elif s[j] == s[i]:
					data[int(s[i])] += 1
					data1 = [1] * 10
			r = max(data)
			data.remove(r)
			ans = max(ans, 2 * max(data))
	print(len(s) - ans)
	return
for t in range(int(ii())):
	solve()


import collections

def checker(x, y):
	x = str(x)
	y = str(y)
	flag = 0
	count = 0
	for char in s:
		if flag == 0:
			if char == x:
				count += 1
				flag = 1
		elif flag == 1:
			if char == y:
				count += 1
				flag = 0
	if count % 2 == 0:
		return count
	return count - 1
for _ in range(int(input())):
	s = input()
	n = len(s)
	dic = collections.Counter(s)
	max_length = 0
	for i in range(10):
		for j in range(10):
			if i == j and str(i) in dic:
				max_length = max(max_length, dic[str(i)])
			elif str(i) in dic and str(j) in dic and (dic[str(i)] + dic[str(j)] > max_length):
				max_length = max(max_length, checker(i, j))
	print(n - max_length)


def solve(s, x, y):
	res = 0
	for ch in s:
		if int(ch) - int('0') == x:
			res += 1
			(x, y) = (y, x)
	if x != y and res % 2 == 1:
		res -= 1
	return res
for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = 0
	for i in range(0, 10):
		for j in range(0, 10):
			ans = max(ans, solve(s, i, j))
	print(n - ans)


def abc(s, x, y):
	m = 0
	i = 0
	while i < len(s):
		if s[i] == x:
			i += 1
			while i < len(s) and s[i] != y:
				i += 1
			if i < len(s):
				m += 1
				i += 1
		else:
			i += 1
	return 2 * m
t = int(input())
for _ in range(t):
	s = input()
	d = {}
	for i in s:
		try:
			d[i] += 1
		except:
			d[i] = 1
	ans = max(d.values())
	for i in range(0, 10):
		for j in range(0, 10):
			ans = max(ans, abc(s, str(i), str(j)))
	print(len(s) - ans)


def solve(s):
	c = [[0] * 10 for _ in range(10)]
	front_appear = [[False] * 10 for _ in range(10)]
	s_cnt = [0] * 10
	for sd in s:
		d = int(sd)
		s_cnt[d] += 1
		for n in range(10):
			if front_appear[n][d]:
				if n != d:
					c[n][d] += 1
					front_appear[n][d] = False
			front_appear[d][n] = True
	cand = len(s) - max(s_cnt)
	max_pair_cnt = 0
	for i in range(10):
		for j in range(10):
			if i != j:
				max_pair_cnt = max(max_pair_cnt, c[i][j])
	cand2 = len(s) - 2 * max_pair_cnt
	ans = min(cand, cand2)
	return ans
t = int(input())
for _ in range(t):
	s = input()
	print(solve(s))


t = int(input())
for _ in range(t):
	s = input()
	data = []
	req = []
	for _ in range(10):
		temp = []
		temp1 = []
		for _ in range(10):
			temp.append(0)
			temp1.append(-1)
		data.append(temp)
		req.append(temp1)
	for i in s:
		i = int(i)
		for j in range(10):
			if req[i][j] == i or req[i][j] == -1:
				data[i][j] += 1
				req[i][j] = j
			if req[j][i] == i and i != j:
				data[j][i] += 1
				req[j][i] = j
	l = []
	for i in range(10):
		for j in range(10):
			if data[i][j] % 2 != 0:
				if i != j:
					data[i][j] = data[i][j] - 1
	for i in data:
		l.append(max(i))
	print(len(s) - max(l))


t = int(input())
for _ in range(t):
	l = [int(i) for i in list(input())]
	ans = float('INF')
	for i in range(10):
		for j in range(10):
			count = 0
			now = 1
			for k in l:
				if now == 1:
					if k != i:
						count += 1
					else:
						now *= -1
				elif k != j:
					count += 1
				else:
					now *= -1
			if i != j and now == -1:
				count += 1
			ans = min(ans, count)
	print(ans)


def giveCost(x, y, s):
	cost = 0
	lookFor = x
	l = 0
	for i in s:
		if i != lookFor:
			cost += 1
		else:
			lookFor = y if lookFor == x else x
			l += 1
	return cost if l % 2 == 0 or x == y else cost + 1
for _ in range(int(input())):
	s = list(map(int, list(input())))
	cost = float('inf')
	for i in range(10):
		for j in range(10):
			cost = min(cost, giveCost(i, j, s))
	print(cost)


from collections import Counter
from itertools import product
t = int(input())
for _ in range(t):
	s = input()
	ans = len(s) - max(Counter(s).values())
	for pair in product('0123456789', repeat=2):
		if pair[0] == pair[1]:
			continue
		index = 0
		cnt = -2
		while index < len(s):
			cnt += 2
			while index < len(s) and s[index] != pair[0]:
				index += 1
			while index < len(s) and s[index] != pair[1]:
				index += 1
		ans = min(ans, len(s) - cnt)
	print(ans)


t = int(input())
for i in range(t):
	lin = input()
	a = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0}
	b = {'0': -1, '1': -1, '2': -1, '3': -1, '4': -1, '5': -1, '6': -1, '7': -1, '8': -1, '9': -1}
	bp = {'0': -1, '1': -1, '2': -1, '3': -1, '4': -1, '5': -1, '6': -1, '7': -1, '8': -1, '9': -1}
	enct = [[0 for k in range(10)] for l in range(10)]
	for j in range(len(lin)):
		a[lin[j]] += 1
		bp[lin[j]] = b[lin[j]]
		b[lin[j]] = j
		for k in range(10):
			if b[str(k)] != -1 and bp[lin[j]] < b[str(k)] and (b[lin[j]] > b[str(k)]):
				enct[int(lin[j])][k] += 1
	max1 = 0
	max2 = 0
	for j in range(10):
		max1 = max(a[str(j)], max1)
		max2 = max(max(enct[j]), max2)
	print(min(len(lin) - 2 * max2, len(lin) - max1))


from collections import defaultdict

def modinv(n, p):
	return pow(n, p - 2, p)

def t():
	return 0

def main():
	for case in range(int(input())):
		counter1 = defaultdict(t)
		counter2 = defaultdict(t)
		s = input()
		n = len(s)
		for x in s:
			counter1[x] += 1
		i = 0
		keys = []
		for i in range(1, 10):
			keys.append('0' + str(i))
		for i in range(10, 100):
			keys.append(str(i))
		for key in keys:
			new_s = []
			finding_first = True
			for c in s:
				if finding_first and c == key[0]:
					new_s.append(c)
					finding_first = False
				elif not finding_first and c == key[1]:
					new_s.append(c)
					finding_first = True
			x = len(new_s)
			counter2[key] = x - x % 2
		a = max(max(list(counter1.values())), max(list(counter2.values())))
		print(n - a)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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 functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	s = input()
	rslt = inf
	for i in range(10):
		for j in range(10):
			x = str(i)
			y = str(j)
			ans = 0
			n = x
			for k in range(len(s)):
				if s[k] == n:
					ans += 1
					if n == x:
						n = y
					else:
						n = x
			if ans % 2 == 1 and x != y:
				ans -= 1
			rslt = min(len(s) - ans, rslt)
	print(rslt)


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')
testcases = int(input())
for j in range(testcases):
	vals = [int(k) for k in input()]
	dict1 = {}
	dict2 = {}
	for s in range(len(vals)):
		if not vals[s] in dict1:
			dict1[vals[s]] = [s]
			dict2[vals[s]] = 1
		else:
			if dict1[vals[s]][-1] + 1 == s:
				dict1[vals[s]][-1] = s
			else:
				dict1[vals[s]].append(s)
			dict2[vals[s]] += 1
	move1 = len(vals) - max(dict2.values())
	maxmove = len(vals)
	for s in range(10):
		if s in dict1:
			for b in dict1.keys():
				if b == s:
					continue
				else:
					p1 = 0
					p2 = 0
					length = 0
					checker = 0
					while p1 < len(dict1[s]) or p2 < len(dict1[b]):
						if p1 == p2 == 0:
							if dict1[s][p1] <= dict1[b][p2]:
								p1 += 1
								checker = 0
							else:
								p2 += 1
								checker = 1
							length += 1
						elif p1 < len(dict1[s]) and p2 < len(dict1[b]):
							if checker == 0:
								if dict1[b][p2] > dict1[s][p1 - 1]:
									length += 1
									checker = 1
								p2 += 1
							else:
								if dict1[s][p1] > dict1[b][p2 - 1]:
									length += 1
									checker = 0
								p1 += 1
						elif checker == 0:
							if p2 < len(dict1[b]):
								if dict1[b][p2] > dict1[s][p1 - 1]:
									length += 1
									break
								p2 += 1
							else:
								break
						elif p1 < len(dict1[s]):
							if dict1[s][p1] > dict1[b][p2 - 1]:
								length += 1
								break
							p1 += 1
						else:
							break
					if len(vals) - (length - length % 2) < maxmove:
						maxmove = len(vals) - (length - length % 2)
	print(min(maxmove, move1))


from collections import Counter

def solve(s):
	best = len(s) - Counter(s).most_common(1)[0][1]
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			count = 0
			for e in s:
				to_find = i if count % 2 == 0 else j
				if int(e) == to_find:
					count += 1
			if count % 2 != 0:
				count -= 1
			best = min(best, len(s) - count)
	return best
n = int(input())
for i in range(n):
	s = input()
	print(solve(s))


def count_maximum_length(string: str, i: str, j: str) -> int:
	last = None
	collection = (i, j)
	result = 0
	for char in string:
		if last is None:
			if char in collection:
				first = char
				last = collection.index(char)
				result += 1
			continue
		if char == collection[1 - last]:
			last = 1 - last
			result += 1
	if first == collection[last] and i != j:
		result -= 1
	return result

def solve() -> int:
	string = input()
	characters = tuple(set(string))
	result = []
	for i in range(len(characters)):
		for j in range(i, len(characters)):
			mlen = count_maximum_length(string, characters[i], characters[j])
			result.append(mlen)
	return len(string) - max(result)
print('\n'.join(map(str, (solve() for _ in range(int(input()))))))


import sys

def main():
	for _ in range(int(input())):
		s = input()
		max_ = 0
		for i in range(10):
			for j in range(10):
				max_ = max(max_, solve(s, str(i), str(j)))
		print(len(s) - max_)

def solve(s1, x, y):
	greed = 0
	for char in s1:
		if char == x:
			greed += 1
			z = x
			x = y
			y = z
	if greed % 2 == 1 and x != y:
		greed -= 1
	return greed
main()


t = int(input())
for i in range(t):
	s = input()
	ans = 0
	e = len(s)
	qr = 0
	for j in range(10):
		for q in range(10):
			b = False
			r = 0
			for i in range(len(s)):
				if j != q:
					if s[i] == str(j) and (not b):
						b = True
						r += 1
					if s[i] == str(q) and b:
						b = False
						r += 1
				elif s[i] == str(j):
					r += 1
			if j == q:
				ans = max(ans, r)
			else:
				r = r - r % 2
				ans = max(ans, r)
	print(e - ans)


for _ in range(int(input())):
	s = input().strip()
	n = len(s)
	freq = [0 for i in range(10)]
	for ch in s:
		freq[ord(ch) - ord('0')] += 1
	freq.sort()
	maxx = 0
	for i in range(10):
		for j in range(i + 1, 10):
			seq = 0
			last = ''
			for ch in s:
				if ch == str(i) or ch == str(j):
					if ch == last:
						continue
					else:
						seq += 1
						last = ch
			if seq % 2 == 1:
				seq -= 1
			if seq > maxx:
				maxx = seq
	maxx = max(maxx, freq[-1])
	print(n - maxx)


for q in range(int(input())):
	line = list(map(int, input()))
	cou = [0] * 10
	for i in line:
		cou[i] += 1
	ans = len(line) - 2
	for i in range(10):
		ans = min(ans, len(line) - cou[i])
	for a in range(10):
		for b in range(10):
			fl = False
			i = 0
			ans_ = 0
			while i < len(line) and line[i] != a:
				i += 1
				ans_ += 1
			i += 1
			while i < len(line):
				while i < len(line) and line[i] != b:
					i += 1
					ans_ += 1
				if i < len(line):
					fl = False
				i += 1
				while i < len(line) and line[i] != a:
					i += 1
					ans_ += 1
				if i < len(line):
					fl = True
				i += 1
			if fl:
				ans_ += 1
			ans = min(ans, ans_)
	print(ans)


import sys
input = sys.stdin.readline
T = int(input())
for testcase in range(1, T + 1):
	s = list(input())
	if s[-1] == '\n':
		s.pop()
	n = len(s)
	for i in range(n):
		s[i] = int(s[i])
	d = [0] * 10
	for e in s:
		d[e] += 1
	res = n - max(d)
	for num in range(100):
		(p, q) = divmod(num, 10)
		if p == q:
			continue
		flag = True
		tmp = 0
		for j in range(n):
			if flag and s[j] == p:
				flag = False
			elif not flag and s[j] == q:
				tmp += 2
				flag = True
		res = min(res, n - tmp)
	print(res)


import math
a = int(input())
for i in range(a):
	total = 0
	s = input()
	ans = []
	count = 1
	maxa = 0
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			count += 1
		else:
			ans.append([count, int(s[i - 1])])
			total += count - 1
			count = 1
	ans.append([count, int(s[-1])])
	total += count - 1
	mini = math.inf
	for i in range(10):
		mini = min(mini, len(s) - s.count(str(i)))
	temp = []
	for i in range(len(ans)):
		temp.append(ans[i][1])
	maxa = 0
	for i in range(10):
		for j in range(10):
			c1 = 0
			if i == j:
				continue
			flag = 0
			for t in range(len(temp)):
				if flag == 0:
					if temp[t] == i:
						c1 += 1
						flag = 1
				if flag == 1:
					if temp[t] == j:
						c1 += 1
						flag = 0
			if c1 % 2 == 0:
				maxa = max(maxa, c1)
	print(min(mini, total + len(temp) - maxa))


from sys import stdin, stdout

def good_string(s):
	dp = [[0 for _ in range(10)] for _ in range(10)]
	cnt = [0] * 10
	ans1 = 0
	ans2 = 0
	for c in s:
		cv = ord(c) - ord('0')
		cnt[cv] += 1
		ans1 = max(ans1, cnt[cv])
		for i in range(10):
			if cv == i:
				continue
			if dp[cv][i] % 2 == 0:
				dp[cv][i] += 1
			if dp[i][cv] % 2 == 1:
				dp[i][cv] += 1
				ans2 = max(dp[i][cv], ans2)
	return len(s) - max(ans1, ans2)
t = int(stdin.readline())
for _ in range(t):
	s = stdin.readline().strip()
	ans = good_string(s)
	stdout.write(str(ans) + '\n')


import os
import sys
from io import BytesIO, IOBase
import math
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')
from collections import defaultdict

def check(s, d):
	n = len(s)
	m = 0
	for i in range(10):
		if m >= d[i]:
			m = m
		else:
			m = d[i]
	r = 87
	v = 10
	for i in range(v):
		for j in range(v):
			ns = 0
			if i == j:
				continue
			t = True
			for k1 in range(n):
				if int(s[k1]) == i and t == True:
					ns += 1
					t = False
				elif int(s[k1]) == j and t == False:
					ns += 1
					t = True
			if ns % 2 == 0:
				if m >= ns:
					m = m
				else:
					m = ns
	return m + 87 - r
for _ in range(int(input())):
	no = input()
	d = defaultdict(int)
	for i in no:
		d[int(i)] += 1
	print(len(no) - check(no, d))


for _ in range(int(input())):
	alpha = [0] * 10
	s = [i for i in input()]
	n = len(s)
	ans = 200000.0 + 1
	for i in range(10):
		for j in range(10):
			(turn, cnt) = (0, 0)
			for x in s:
				if int(x) == i and turn == 0:
					turn += 1
					turn %= 2
					cnt += 1
				elif int(x) == j and turn == 1:
					turn += 1
					turn %= 2
					cnt += 1
			if cnt % 2 == 1 and i != j:
				cnt -= 1
			ans = min(ans, n - cnt)
	print(ans)


def hhh(s, u, v):
	c = b = 0
	for i in range(len(s)):
		if b == 0:
			if s[i] == u:
				x = u
				y = v
				b = 1
			elif s[i] == v:
				x = v
				y = u
				b = 1
		elif b == 1:
			if s[i] == y:
				c += 2
				b = 2
		elif s[i] == x:
			b = 1
	return c
for t in range(int(input())):
	s = input()
	a = []
	for i in range(10):
		a.append(s.count(str(i)))
	m = max(a)
	for i in range(10):
		for j in range(i + 1, 10):
			n = hhh(s, str(i), str(j))
			if n > m:
				m = n
	print(len(s) - m)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))
ilelec = lambda : map(int1, input().split())
alelec = lambda : list(map(int1, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = n - 2
	if ans == 0:
		print(0)
		continue
	for i in range(0, 10):
		for j in range(0, 10):
			c = [str(i), str(j)]
			x = 0
			count = 0
			for k in s:
				if k == c[x]:
					count += 1
					x ^= 1
			if x == 1:
				count -= 1
			ans = min(ans, n - count)
	C = Counter(s)
	maxi = C.most_common(1)
	ans = min(ans, n - maxi[0][1])
	print(ans)


t = int(input())
for _ in range(0, t):
	st = str(input())
	if len(st) <= 2:
		print(0)
		continue
	ans = 2
	for i in range(10):
		for j in range(10):
			temp = 0
			for char in st:
				if temp & 1:
					if char == str(j):
						temp += 1
				elif char == str(i):
					temp += 1
			if i != j:
				if temp & 1:
					temp -= 1
			ans = max(ans, temp)
	print(len(st) - ans)


def count(s, a):
	b = 0
	cur = 0
	for i in s:
		if i == a[0]:
			b = 1
		elif b and i == a[1]:
			cur += 1
			b = 0
	return cur
t = int(input())
for k in range(t):
	s = input()
	mx = 0
	for i in range(10):
		for j in range(10):
			if i == j:
				mx = max(mx, s.count(str(i)))
			else:
				s1 = str(i) + str(j)
				mx = max(mx, 2 * count(s, s1))
	print(len(s) - mx)


from collections import Counter
for _ in range(int(input())):
	s = input()
	n = len(s)
	c = Counter(s)
	m = c.most_common()
	out = m[0][1]
	for i in range(100):
		y = str(i)
		if i < 10:
			y = '0' + y
		cnt = 0
		f = 0
		if c[y[0]] + c[y[1]] > out:
			for k in range(n):
				if s[k] == y[0]:
					f = 1
				elif s[k] == y[1] and f == 1:
					cnt += 1
					f = 0
			out = max(2 * cnt, out)
	print(len(s) - out)


def readGenerator():
	while True:
		tokens = input().split(' ')
		for t in tokens:
			yield t
reader = readGenerator()

def readWord():
	return next(reader)

def readInt():
	return int(next(reader))

def readFloat():
	return float(next(reader))

def readLine():
	return input()
tests = readInt()

def solve(n):
	return n
for t in range(0, tests):
	s = readLine()
	res = len(s)
	for i in range(0, 10):
		res = min(res, len(s) - s.count(str(i)))
	for i in range(0, 10):
		for j in range(0, 10):
			p = str(i) + str(j)
			f = 0
			for v in s:
				if v == p[f % 2]:
					f += 1
			res = min(res, len(s) - 2 * (f // 2))
	print(res)


for _ in range(int(input())):
	s = input()
	we = len(s)
	d = {}
	l = []
	for i in s:
		if i not in d:
			d[i] = 1
		else:
			d[i] += 1
	for i in d:
		l.append(d[i])
	l_pair = []
	for i in d:
		for j in d:
			if i != j:
				ss = i + j
				l_pair.append(ss)
	for i in range(len(l_pair)):
		cnt = 0
		flag = 0
		for j in range(we):
			if flag == 0 and s[j] == l_pair[i][0]:
				flag = 1
			elif flag == 1 and s[j] == l_pair[i][1]:
				cnt += 1
				flag = 0
		l.append(cnt * 2)
	an = max(max(l), 2)
	print(we - an)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	s = input().rstrip()
	l = len(s)
	b = 9999999
	for i in range(10):
		k = s.count(str(i))
		b = min(b, l - k)
	b_count = 0
	for i in range(10):
		for j in range(10):
			count = 0
			last = str(j)
			for c in s:
				if (c == str(j) or c == str(i)) and c != last:
					count += 1
					last = c
			b_count = max(count, b_count)
	bb = b_count // 2 * 2
	print(min(b, l - bb))


for _ in range(int(input())):
	s = input()
	n = len(s)
	ar = [0] * 10
	mx = 0
	if n <= 2:
		print(0)
		continue
	for i in range(10):
		for j in range(10):
			f = True
			cnt = 0
			for k in range(n):
				if f:
					if int(s[k]) == i:
						f = not f
						cnt += 1
				elif int(s[k]) == j:
					f = not f
					cnt += 1
			if i != j and (not f):
				cnt -= 1
			mx = max(mx, cnt)
	print(n - mx)


for _ in range(int(input())):
	n = input()
	cnt = 2
	f = [0 for i in range(10)]
	for i in range(10):
		for c in n:
			if c == str(i):
				f[i] += 1
		for j in range(i + 1, 10):
			(ind1, ind2) = (True, True)
			(cnt1, cnt2) = (0, 0)
			for c in n:
				if ind1 and c == str(i):
					ind1 = False
				if not ind1 and c == str(j):
					ind1 = True
					cnt1 += 2
			for c in n:
				if ind2 and c == str(j):
					ind2 = False
				if not ind2 and c == str(i):
					ind2 = True
					cnt2 += 2
			cnt = max(cnt, cnt1, cnt2)
	x = max(f)
	cnt = max(cnt, x)
	print(len(n) - cnt)


t = int(input())
while t:
	s = input()
	arr = [0] * 10
	ans = 10000000
	for i in s:
		arr[int(i)] += 1
	for i in range(10):
		for j in range(i):
			if not arr[i] or not arr[j]:
				continue
			cnt = 0
			cntt = 0
			for k in s:
				if cnt % 2 == 0 and int(k) == i or (cnt % 2 == 1 and int(k) == j):
					cnt += 1
				if cntt % 2 == 0 and int(k) == j or (cntt % 2 == 1 and int(k) == i):
					cntt += 1
			ans = min(ans, len(s) - cnt + cnt % 2)
			ans = min(ans, len(s) - cntt + cntt % 2)
	for i in arr:
		ans = min(ans, len(s) - i)
	print(ans)
	t -= 1


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	s = inputstring()
	ans = 0
	nums = [0] * 58
	for c in s:
		nums[ord(c)] += 1
		ans = max(ans, nums[ord(c)])
	for c in range(48, 58):
		for d in range(48, 58):
			first = True
			length = 0
			for i in range(len(s)):
				if first and s[i] == chr(c):
					first = False
					length += 1
				elif not first and s[i] == chr(d):
					first = True
					length += 1
			ans = max(ans, length - (length % 2 == 1))
	print(len(s) - ans)


for _ in range(int(input())):
	s = input().strip()
	c = [[0 for i in range(10)] for i in range(10)]
	for i in s:
		d = int(i)
		for p in range(10):
			c[d][p] = c[p][d] + 1
	print(len(s) - max(max([max(k) for k in c]) // 2 * 2, max([c[i][i] for i in range(10)])))


def fun(s, a, b):
	ct = 0
	for i in s:
		if i == a:
			(a, b) = (b, a)
			ct += 1
	if ct % 2 != 0:
		return ct - 1
	return ct
for _ in range(int(input())):
	s = input()
	n = len(s)
	d = {}
	maxi = 0
	for i in range(10):
		for j in range(10):
			if i == j:
				x = s.count(str(i))
			else:
				x = fun(s, str(i), str(j))
			if maxi < x:
				maxi = x
	print(n - maxi)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

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

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

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

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

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

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		s = insr()
		freq = [0 for i in range(10)]
		for i in range(len(s)):
			s[i] = int(s[i])
			freq[s[i]] = freq[s[i]] + 1
		ans = len(s) - max(freq)

		def helper(s, num):
			j = 0
			for i in s:
				if i == num[j % 2]:
					j = j + 1
			if j % 2 != 0:
				j = j - 1
			return j
		for i in range(10):
			for j in range(10):
				ans = min(ans, len(s) - helper(s, [i, j]))
		print(ans)
main()


import string
t = int(input())
for _ in range(t):
	s = input()
	l = [0] * 10
	for i in s:
		l[int(i)] += 1
	ans1 = len(s) - max(l)
	for i in range(0, 10):
		for j in range(0, 10):
			if i != j:
				count = 0
				flag = 0
				for k in s:
					k = int(k)
					if flag == 0 and k == i:
						flag = 1
					elif k == j and flag == 1:
						flag = 0
						count += 2
				ans1 = min(ans1, len(s) - count)
	print(ans1)


T = int(input())
for _ in range(T):
	s = input()
	n = len(s)
	ans = n - 2
	A = [0 for i in range(10)]
	for i in range(10):
		for j in range(10):
			l = 0
			st = 0
			B = [str(i), str(j)]
			for val in s:
				if val == B[st]:
					l = l + 1
					st = (st + 1) % 2
			if i != j:
				if l % 2 != 0:
					l = l - 1
				ans = min(ans, n - l)
			else:
				ans = min(ans, n - l)
	print(ans)


for i in range(int(input())):
	s = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			c = str(i)
			l = 0
			for k in s:
				if k == c:
					l += 1
					c = str(i) if c == str(j) else str(j)
			if l & 1 and i != j:
				l -= 1
			ans = max(ans, l)
	print(len(s) - ans)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
MOD = 1000000007

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
char = '0123456789'

def check(a, b):
	key = {1: a, 0: b}
	ind = 1
	length = 0
	for i in s:
		if i == key[ind]:
			length += 1
			ind ^= 1
	ans = length
	if a != b:
		ans = length - length % 2
	return ans
for _ in range(Int()):
	s = input()
	ans = 0
	for i in char:
		for j in char:
			ans = max(ans, check(i, j))
	print(len(s) - ans)


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	s = sys.stdin.readline().strip()
	l = len(s)
	S = [int(s[i]) for i in range(0, l)]
	ans = l
	for i in range(0, 10):
		for j in range(0, 10):
			if i == j:
				ans = min(ans, l - S.count(i))
			else:
				v = True
				c = 0
				for k in range(0, l):
					if v == True and S[k] == i:
						v = False
					elif v == False and S[k] == j:
						v = True
						c = c + 1
				ans = min(ans, l - 2 * c)
	print(ans)


from sys import stdin, stdout
q = int(input())
for i in range(q):
	s = input()
	sum1 = 0
	flag = 0
	for i in range(10):
		for j in range(10):
			maxi = 0
			flag = 0
			for k in s:
				if flag == 0:
					if int(k) == i:
						maxi += 1
						flag = 1
				elif int(k) == j:
					maxi += 1
					flag = 0
			if i != j:
				maxi -= maxi % 2
			sum1 = max(maxi, sum1)
	print(len(s) - sum1)


def checker(a, b, arr):
	fr = [-1, -1]
	for i in range(len(arr)):
		if arr[i] == a or arr[i] == b:
			if fr[0] == -1 and fr[1] == -1:
				if arr[i] == b:
					(a, b) = (b, a)
				fr[0] = 1
				fr[1] = 0
			elif arr[i] == a and fr[0] == fr[1]:
				fr[0] += 1
			elif arr[i] == b and fr[1] == fr[0] - 1:
				fr[1] += 1
	an = max(min(fr) * 2, ar[0][0])
	return an
test = int(input())
for _ in range(test):
	arr = list(input())
	if len(arr) == 1 or len(arr) == 2:
		print(0)
	else:
		freq = {}
		maxf = 0
		for i in range(len(arr)):
			freq[arr[i]] = freq.get(arr[i], 0) + 1
			maxf = max(maxf, freq[arr[i]])
		if len(freq) == len(arr):
			print(len(arr) - 2)
		elif len(freq) == 1:
			print(0)
		else:
			maxnn = 0
			ar = []
			for (k, v) in freq.items():
				ar.append((v, k))
			for i in range(10):
				for j in range(i + 1, 10):
					nn = checker(str(i), str(j), arr)
					maxnn = max(maxnn, nn)
			print(len(arr) - max(maxf, maxnn))


def solve(s):
	ans = 0
	for i in range(0, 10):
		c1 = str(i)
		for j in range(0, 10):
			c2 = str(j)
			state = 0
			sum = 0
			for k in range(len(s)):
				if state == 0:
					if c1 == s[k]:
						state = 1
				elif c2 == s[k]:
					sum += 2
					state = 0
			if c1 == c2 and state == 1:
				sum += 1
			ans = max(ans, sum)
	print(len(s) - ans)
t = int(input())
for _ in range(t):
	s = input()
	solve(s)


from itertools import combinations
from collections import Counter
for _ in range(int(input())):
	string = input()
	se = set()
	dic = Counter(string)
	for i in string:
		if i not in se:
			se.add(i)
	l = list(combinations(se, 2))
	z = []
	min1 = float('Inf')
	for i in l:
		z = []
		for j in string:
			if j in i:
				if len(z) and z[-1] == j:
					continue
				z.append(j)
		if len(z) % 2 == 0:
			min1 = min(min1, len(string) - len(z))
		else:
			min1 = min(min1, len(string) - len(z) + 1)
	for i in dic:
		min1 = min(min1, len(string) - dic[i])
	print(min1)


def solve(l, i, j):
	ans = 0
	for x in l:
		if x == i:
			ans += 1
			(i, j) = (j, i)
	if i != j and ans % 2 == 1:
		ans -= 1
	return ans
for _ in range(int(input())):
	l = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			ans = max(ans, solve(l, str(i), str(j)))
	print(len(l) - ans)


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

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

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 10 ** 7 + 1
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

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
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

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

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)

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

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

def string_list():
	return list(input())

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

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	maxint = 10 ** 10
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def solve():
	s = input()
	n = len(s)
	if n == 2:
		print(0)
		return
	occur = {}
	for i in range(n):
		try:
			occur[s[i]].append(i)
		except KeyError:
			occur[s[i]] = [i]
	num = list(sorted(occur.keys()))
	ans = 10 ** 10
	max_length = 0
	for i in num:
		for j in num:
			max_length = max(max_length, len(occur[i]), len(occur[j]))
			if i == j:
				continue
			indx1 = indx2 = 0
			c = 0
			while indx1 < len(occur[i]):
				while indx2 < len(occur[j]) and occur[j][indx2] < occur[i][indx1]:
					indx2 += 1
				if indx2 == len(occur[j]):
					break
				c += 2
				indx2 += 1
				indx1 += 1
				if indx1 < len(occur[i]) and indx2 < len(occur[j]):
					while indx1 < len(occur[i]) and occur[i][indx1] < occur[j][indx2 - 1]:
						indx1 += 1
			ans = min(ans, n - c)
	print(min(ans, n - max_length))
t = 1
t = int(input())
for _ in range(t):
	solve()


def solve():
	s = input()
	n = len(s)
	dic = {}
	occ = {}
	for i in range(0, n):
		if s[i] not in dic:
			dic[s[i]] = [i]
			occ[s[i]] = 1
		else:
			dic[s[i]].append(i)
			occ[s[i]] += 1
	dic2 = {}
	maxx = 2
	for d in dic:
		others = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0}
		maxx_others = 0
		if len(dic[d]) <= 1:
			continue
		for i in range(len(dic[d])):
			st = dic[d][i]
			if i + 1 < len(dic[d]):
				end = dic[d][i + 1]
				sets = set(s[st + 1:end])
				for i in sets:
					others[i] += 1
					maxx_others = max(maxx_others, others[i])
			elif i + 1 == len(dic[d]):
				end = n
				sets = set(s[st + 1:end])
				for i in sets:
					others[i] += 1
					maxx_others = max(maxx_others, others[i])
		maxx1 = max(occ[d], maxx_others * 2)
		maxx = max(maxx1, maxx)
	print(n - maxx)
t = int(input())
for i in range(t):
	solve()


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
from collections import Counter as cc
from bisect import bisect as bi
(t,) = I()
for _ in range(t):
	s = input().strip()
	p = cc(s)
	an = max(p.values())
	l = [[] for i in range(10)]
	for i in range(10):
		cr = chr(ord('0') + i)
		if s[0] == cr:
			l[i].append(0)
		for j in range(1, len(s)):
			if s[j] == cr and s[j - 1] != cr:
				l[i].append(j)
	for i in range(10):
		for j in range(i + 1, 10):
			x = list(l[i])
			y = list(l[j])
			if x and y:
				ct = 0
				if x[0] > y[0]:
					x = l[j].copy()
					y = l[i].copy()
				if 1:
					kk = []
					for pp in range(len(y)):
						st = bi(x, y[pp])
						if kk:
							if st != kk[-1]:
								kk.append(st)
						else:
							kk.append(st)
					ct = 2 * len(kk)
				an = max(ct, an)
	print(len(s) - an)


for _ in range(int(input())):
	a = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			t = 0
			for s in a:
				if t % 2:
					if int(s) == i:
						t += 1
				elif int(s) == j:
					t += 1
			if i != j:
				t = t // 2 * 2
			ans = max(ans, t)
	print(len(a) - ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	t = stdin.readline().strip()
	array = [[0 for i in range(10)] for j in range(10)]
	flag = [[0 for i in range(10)] for j in range(10)]
	ans = 0
	freq = [0] * 10
	for i in t:
		x = int(i)
		freq[x] += 1
		for j in range(10):
			flag[x][j] = 1
		for j in range(10):
			if flag[j][x] == 1:
				array[j][x] += 1
				flag[j][x] = 0
	ans = max(freq)
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			ans = max(ans, 2 * array[i][j])
	print(len(t) - ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def calc(s, a, b):
	temp = 0
	for i in s:
		if i == a:
			(a, b) = (b, a)
			temp += 1
	if temp & 1:
		temp -= 1
	return temp
t = int(input())
for _ in range(t):
	s = [int(x) for x in input()]
	n = len(s)
	cnt = {}
	for x in range(10):
		cnt[x] = s.count(x)
	ans = n
	for x in range(10):
		for y in range(10):
			if x in cnt and y in cnt:
				if x == y:
					ans = min(ans, n - cnt[x])
				else:
					temp1 = calc(s, x, y)
					temp2 = calc(s, y, x)
					temp = min(n - temp1, n - temp2)
					ans = min(ans, temp)
	print(ans)


import os
from sys import stdin, stdout

def solve(tc):
	s = stdin.readline().strip()
	nums = [0 for i in range(10)]
	for c in s:
		nums[ord(c) - ord('0')] += 1
	maxnum = 0
	for i in range(10):
		maxnum = max(maxnum, nums[i])
	ans = maxnum
	for i in range(10):
		if nums[i] == 0:
			continue
		for j in range(10):
			if nums[j] == 0:
				continue
			cnt = 0
			for k in range(len(s)):
				if cnt % 2:
					if ord(s[k]) - ord('0') == j:
						cnt += 1
				elif ord(s[k]) - ord('0') == i:
					cnt += 1
			if cnt % 2:
				cnt -= 1
			ans = max(ans, cnt)
	print(len(s) - ans)
tcs = 1
tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
	solve(tc)
	tc += 1


t = int(input())

def max_len(two, num):
	two = str(two)
	if len(two) == 1:
		two = '0' + two
	lenth = 0
	to_check = 0
	for i in num:
		if i == two[to_check]:
			to_check = (to_check + 1) % 2
			lenth += 1
	if lenth % 2 == 0:
		return lenth
	return lenth - 1

def solve():
	num = input()
	freq = {}
	for i in num:
		freq[i] = freq.get(i, 0) + 1
	maxx = max(freq.values())
	can = maxx
	for i in range(100):
		can = max(can, max_len(i, num))
	print(len(num) - can)
while t:
	solve()
	t -= 1


import sys
input = sys.stdin.readline
import math

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

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

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

def from_file(f):
	return f.readline

def count(l, a, b):
	res = 0
	expect = a
	for c in l:
		if int(c) != expect:
			res += 1
		else:
			expect = b if expect == a else a
	left = len(l) - res
	if left % 2 == 1 and a != b:
		res += 1
	return res

def solve(l):
	m = len(l)
	for a in range(10):
		for b in range(10):
			m = min(m, count(l, a, b))
	return m
t = inp()
for _ in range(t):
	l = input().strip()
	print(solve(l))


import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	s = list(map(int, list(ns())))
	ans = 0
	for i in range(10):
		for j in range(10):
			(a, b) = (i, j)
			c = 0
			for x in s:
				if x == a:
					(a, b) = (b, a)
					c += 1
			if a != b:
				c &= ~1
			if ans < c:
				ans = c
	print(len(s) - ans)
	return
T = ni()
for _ in range(T):
	solve()


tt = int(input())
while tt != 0:
	n = input()
	d = {}
	for i in range(10):
		d[i] = 0
	for i in range(len(n)):
		d[int(n[i])] += 1
	maxi = 0
	for i in d.keys():
		maxi = max(maxi, d[i])
	ans = len(n) - maxi
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			else:
				k = 0
				t = 0
				while k < len(n):
					(f1, f2) = (0, 0)
					while k < len(n):
						if int(n[k]) == i:
							f1 = 1
							break
						k += 1
					if f1 == 1:
						while k < len(n):
							if int(n[k]) == j:
								f2 = 1
								break
							k += 1
					if f1 == 0 or f2 == 0:
						break
					else:
						t += 2
				ans = min(ans, len(n) - t)
	print(ans)
	tt -= 1


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(3 * 10 ** 6)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

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 get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def isSubsetSum(arr, n, summ):
	subarr = [[False for i in range(summ + 1)] for i in range(n + 1)]
	for i in range(n + 1):
		subarr[i][0] = True
	for i in range(1, summ + 1):
		subarr[0][i] = False
	for i in range(1, n + 1):
		for j in range(1, summ + 1):
			if j < arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j]
			if j >= arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j] or subarr[i - 1][j - arr[i - 1]]
	return subarr[n][summ]

def bfs(v, adj, onpath):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

@bootstrap
def dfs(v, p, adj, b, path):
	if v == b:
		path.append(b)
		yield True
	for u in adj[v]:
		if u == p:
			continue
		on = (yield dfs(u, v, adj, b, path))
		if on:
			path.append(v)
			yield True
	yield False

@bootstrap
def dfs1(v, p, adj, d, mcd, onpath, c, root):
	if len(mcd) < d + 1:
		mcd.append([c[v], d, root, v])
	if mcd[d][0] > c[v]:
		mcd[d][0] = c[v]
		mcd[d][3] = v
	for u in adj[v]:
		if u == p or onpath[u]:
			continue
		yield dfs1(u, v, adj, d + 1, mcd, onpath, c, root)
	yield False

def solution(s):
	n = len(s)
	s = [int(x) for x in s]
	min_opt = min([n - s.count(i) for i in range(10)])
	order = []
	num = len(set(s))
	for i in range(n):
		if s[i] in order:
			continue
		order.append(s[i])
		if len(order) == num:
			break
	for io in range(len(order) - 1):
		for jo in range(io + 1, len(order)):
			i = order[io]
			j = order[jo]
			k = 0
			while k < n and s[k] != i and (s[k] != j):
				k += 1
			if k == n:
				continue
			first = last = s[k]
			other = i if s[k] == j else j
			cnt = k
			for l in range(k + 1, n):
				if s[l] == other:
					(other, last) = (last, other)
					continue
				cnt += 1
			if last == first:
				cnt += 1
			min_opt = min(min_opt, cnt)
	return min_opt

def main():
	T = 1
	T = ri()
	for i in range(T):
		s = rs()
		x = solution(s)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	ans = n
	for i in range(10):
		cnt = 0
		for c in s:
			if int(c) == i:
				cnt += 1
			ans = min(ans, n - cnt)
	for c1 in range(10):
		for c2 in range(10):
			if c1 != c2:
				length = 0
				findc1 = True
				for c in s:
					if findc1 == True and int(c) == c1:
						findc1 = False
					elif findc1 == False and int(c) == c2:
						length += 2
						findc1 = True
				ans = min(ans, n - length)
	print(ans)


from collections import Counter

def main():
	t = Iint()
	for _ in range(t):
		s = I()
		c = Counter(s)
		ca = c.most_common()
		ans = ca[0][1]
		for i in range(10):
			for j in range(10):
				xi = chr(ord('0') + i)
				xj = chr(ord('0') + j)
				if xi == xj:
					continue
				count = 0
				ati = True
				for si in s:
					if ati and si == xi:
						ati = False
					if not ati and si == xj:
						ati = True
						count += 1
				count *= 2
				if count > ans:
					ans = count
		print(len(s) - ans)
FIO = 1

def I():
	return input()

def Iint():
	return int(input())

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

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

def Plist(li, s=' '):
	print(s.join(map(str, li)))
en = enumerate
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import sys
	import os
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 input():
	return sys.stdin.readline().rstrip('\r\n')
main()


def getmax(s):
	reps = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	matrix = ([0, [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], 0, [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], 0, [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], 0, [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], 0, [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], 0, [-1, 0], [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], 0, [-1, 0], [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], 0, [-1, 0], [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], 0, [-1, 0]], [[-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], [-1, 0], 0])
	maxpair = 0
	for i in range(len(s)):
		x = int(s[i])
		reps[x] += 1
		for y in range(10):
			if x != y:
				current = matrix[y][x][0]
				if current == y:
					matrix[y][x][0] = x
					matrix[y][x][1] += 1
					if matrix[y][x][1] > maxpair:
						maxpair = matrix[y][x][1]
				current = matrix[x][y][0]
				if current != x:
					matrix[x][y][0] = x
					if matrix[x][y][1] > maxpair:
						maxpair = matrix[x][y][1]
	maxrep = max(reps)
	maxpair = maxpair * 2
	return maxpair if maxpair > maxrep else maxrep
n = int(input())
for t in range(n):
	s = input()
	print(len(s) - getmax(s))


from collections import Counter
from operator import itemgetter
for x in range(int(input())):
	s = input()
	n = len(s)
	p = {}
	for i in range(n):
		if s[i] not in p:
			p[s[i]] = i
	d = Counter(s)
	j = sorted(d.items(), key=itemgetter(1), reverse=True)
	if j[0][1] > n // 2:
		print(n - j[0][1])
	else:
		mx = j[0][1]
		for i in range(len(j) - 1):
			for u in range(i + 1, len(j)):
				if p[j[i][0]] < p[j[u][0]]:
					t = 0
				else:
					t = 1
				r = t
				l = 0
				for k in range(n):
					if s[k] == j[i][0] and t == 0:
						l += 1
						t = 1 - t
					elif s[k] == j[u][0] and t == 1:
						l += 1
						t = 1 - t
				if t != r:
					l -= 1
				mx = max(mx, l)
		print(n - mx)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
import collections as col

def solve():
	S = [int(s) for s in input()]
	N = len(S)
	S_count = col.defaultdict(int)
	for s in S:
		S_count[s] += 1
	max_count = 0
	for s in S_count:
		max_count = max(S_count[s], max_count)
	best = max_count
	for i in range(10):
		for j in range(10):
			if i == j or S_count[i] + S_count[j] <= best:
				continue
			curr_need = i
			count = 0
			ind = 0
			while ind < N:
				while ind < N and S[ind] != curr_need:
					ind += 1
				if ind < N:
					count += 1
					if curr_need == i:
						curr_need = j
					else:
						curr_need = i
				ind += 1
			if count % 2 == 1:
				count -= 1
			best = max(count, best)
	return N - best
T = getInt()
for t in range(T):
	print(solve())


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

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	s = input().strip()
	n = len(s)
	ma = 0
	mi = 10
	for j in s:
		ma = max(ma, int(j))
		mi = min(mi, int(j))
	ans = 0
	for j in range(mi, ma + 1):
		for k in range(mi, ma + 1):
			if j == k:
				c = s.count(str(j))
			else:
				c = 0
				flag = 0
				for ch in s:
					if flag == 0 and int(ch) == j:
						flag = 1
					elif flag == 1 and int(ch) == k:
						flag = 0
						c += 2
			ans = max(ans, c)
	print(n - ans)


t = int(input())
for _ in range(t):
	st = input()
	ans = 2000001
	l = len(st)
	s = set(st)
	for j in s:
		c = st.count(j)
		if l - c < ans:
			ans = l - c
	arr = []
	for j in s:
		arr.append(j)
	for i in range(len(arr)):
		for j in range(i + 1, len(arr)):
			count = 0
			last = 0
			for k in range(l):
				if last == 0:
					if st[k] == arr[i]:
						count += 1
						last = 1
				elif st[k] == arr[j]:
					count += 1
					last = 0
			if count % 2 == 0:
				if l - count < ans:
					ans = l - count
			count = 0
			last = 1
			for k in range(l):
				if last == 0:
					if st[k] == arr[i]:
						count += 1
						last = 1
				elif st[k] == arr[j]:
					count += 1
					last = 0
			if count % 2 == 0:
				if l - count < ans:
					ans = l - count
	print(ans)


from collections import defaultdict as dd
for _ in range(int(input())):
	s = input().strip()
	n = len(s)
	l = [0] * 10
	s = list(s)
	for i in range(0, n):
		s[i] = int(s[i])
		l[s[i]] += 1
	ans = n - max(l)
	for i in range(0, 10):
		for j in range(0, 10):
			ct = 0
			if i != j:
				fg = 0
				for k in range(0, n):
					if s[k] == i:
						fg = 1
					elif s[k] == j and fg == 1:
						ct += 2
						fg = 0
				ans = min(ans, n - ct)
	print(ans)


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')

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

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

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

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def toord(c):
	return ord(c) - ord('a')
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		s = input()
		res = len(s) - 2
		rec = [0] * 10
		for i in range(len(s)):
			now = int(s[i])
			rec[now] += 1
			res = min(res, len(s) - rec[now])
		for i in range(10):
			rec = [0] * 10
			pre = -1
			now = [0] * 10
			for j in range(len(s)):
				if pre != -1:
					now[int(s[j])] = 1
				if int(s[j]) == i or j == len(s) - 1:
					if pre != -1:
						for k in range(10):
							if i == k:
								continue
							if now[k] == 1:
								rec[k] += 1
						res = min(res, len(s) - 2 * max(rec))
					pre = j
					now = [0] * 10
		print(res)
main()


def solve(s, n):
	ans = n - 1
	for a in range(10):
		for b in range(10):
			cnt1 = 0
			cnt2 = 0
			f = 'fst'
			for i in range(n):
				if f == 'fst':
					if s[i] == a:
						cnt1 += 1
						f = 'snd'
				elif s[i] == b:
					cnt2 += 1
					f = 'fst'
			if a != b:
				res = min(cnt1, cnt2) * 2
			else:
				res = cnt1 + cnt2
			ans = min(ans, n - res)
	return ans

def main():
	t = int(input())
	for i in range(t):
		a = [int(i) for i in input()]
		print(solve(a, len(a)))
main()


from sys import stdin, stdout

def input():
	return stdin.readline().strip()
T = int(input())

def ans1(S):
	return max((S.count(i) for i in '0123456789'))

def ans2(S):
	ret = float('-inf')
	for i in '0123456789':
		for j in '0123456789':
			ret = max(ret, ans3(S, i, j))
	return ret

def ans3(S, a, b):
	na = 0
	nb = 0
	for c in S:
		if na == nb and c == a:
			na += 1
		elif na == nb + 1 and c == b:
			nb += 1
	return 2 * nb

def ans(S):
	return len(S) - max(ans1(S), ans2(S))
for _ in range(T):
	S = input()
	print(ans(S))


def solve():
	s = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			(x, y) = (str(i), str(j))
			l = 0
			for ch in s:
				if ch == x:
					l += 1
					(x, y) = (y, x)
			if l % 2 != 0 and x != y:
				l -= 1
			ans = max(ans, l)
	print(len(s) - ans)
for case in range(int(input())):
	solve()


from collections import Counter
for i in range(int(input())):
	s = list(input())
	n = len(s)
	z = Counter(s)
	an = 0
	for j in range(10):
		for k in range(10):
			if k == j:
				continue
			an1 = 0
			flag = False
			for x in s:
				if flag == False and x == str(j):
					flag = True
				elif flag and x == str(k):
					flag = False
					an1 += 2
				an = max(an, an1)
	print(min(n - an, n - z[max(z, key=z.get)]))


def calc(a, b, s):
	t = 0
	for i in range(len(s)):
		if t & 1 and s[i] == b:
			t += 1
		elif t & 1 == 0 and s[i] == a:
			t += 1
	return len(s) - t // 2 * 2
for _ in range(int(input())):
	s = input()
	ans = 1000000
	for i in range(0, 10):
		temp = s.count(str(i)[0])
		if temp & 1 == 0:
			temp -= 1
		ans = min(ans, len(s) - temp)
		ans = min(ans, calc('0', str(i), s))
	for i in range(10, 100):
		s1 = str(i)
		a = s1[0]
		b = s1[1]
		ans = min(ans, calc(a, b, s))
	print(ans)


from collections import defaultdict
for _ in range(int(input())):
	x = input()
	n = len(x)
	a = []
	for i in x:
		a.append(int(i))
	c = [0] * 10
	d = [[[0, -1] for _ in range(10)] for _ in range(10)]
	v = [0] * 10
	c[a[0]] = 1
	count = 2
	v[a[0]] = 1
	for i in range(1, n):
		no = a[i]
		c[no] += 1
		if v[no] == 0:
			for j in range(10):
				if v[j] != 0:
					d[j][no][0] = 2
					d[j][no][1] = no
			v[no] = count
			count += 1
		else:
			for j in range(10):
				if d[no][j][1] == j:
					d[no][j][0] += 1
					d[no][j][1] = no
			for j in range(10):
				if d[j][no][1] == j:
					d[j][no][0] += 1
					d[j][no][1] = no
	cm = max(c)
	m = 2
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			m = max(d[i][j][0], m)
	print(n - max(cm, m // 2 * 2))


from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	s = input()
	MIN = 10 ** 9
	for g in range(10):
		for l in range(10):
			ans = 0
			st = str(g)
			now = st
			for m in range(len(s)):
				if s[m] == now:
					if now == str(g):
						now = str(l)
					else:
						now = str(g)
				else:
					ans += 1
			if st != now:
				ans += 1
			MIN = min(MIN, ans)
	print(MIN)


from sys import stdin

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

def r_t(tp):
	return map(tp, r().strip().split())

def r_a(tp):
	return list(r_t(tp))

def solve(t):
	occur = [0 for _ in range(10)]
	for x in t:
		occur[int(x)] += 1
	ans = float('inf')
	for x in occur:
		ans = min(ans, len(t) - x)
	for i in range(10):
		for j in range(10):
			(a, b, u, cnt) = (str(i), str(j), 'a', 0)
			for x in t:
				if x == a and u == 'a':
					u = 'b'
				elif x == b and u == 'b':
					cnt += 2
					u = 'a'
			ans = min(ans, len(t) - cnt)
	return ans

def main():
	cases = int(r())
	for case in range(cases):
		t = r()
		print(solve(t))
main()


t = int(input())
for case in range(t):
	s = list(map(int, list(input())))
	maxCounter = 0
	for i in range(10):
		for j in range(10):
			prev = -1
			counter = 0
			for k in s:
				if (k == i or k == j) and (i != j and k != prev or i == j):
					counter += 1
					prev = k
			if i != j:
				if counter % 2 == 1:
					counter -= 1
			if counter > maxCounter:
				maxCounter = counter
	print(len(s) - maxCounter)


for _ in range(int(input())):
	s = input().strip()
	dp = [0] * 10
	for c in s:
		dp[ord(c) - ord('0')] += 1
	ans = max(dp)
	for i in range(10):
		for j in range(i + 1, 10):
			(a, b) = (str(i), str(j))
			f = None
			cnt = 0
			for c in s:
				if c == a:
					if f == None:
						f = True
						cnt = 1
					elif f == False:
						cnt += 1
						f = not f
				elif c == b:
					if f == None:
						f = False
						cnt = 1
					elif f == True:
						cnt += 1
						f = not f
			ans = max(ans, cnt - cnt % 2)
	print(len(s) - ans)


t = int(input())
for _ in range(t):
	s = input()
	span = []
	for i in range(10):
		for j in range(10):
			span.append(str(i) + str(j))
	ans = 0
	for i in range(100):
		toggle = 0
		cnt = 0
		prev = ans
		for j in range(len(s)):
			if s[j] == span[i][toggle]:
				cnt += 1
				toggle = 1 - toggle
			if span[i][0] != span[i][1]:
				ans = max(ans, cnt // 2 * 2)
			else:
				ans = max(ans, cnt)
		if prev != ans:
			char = span[i]
	print(len(s) - ans)


(z, zz) = (input, lambda : list(map(int, z().split())))
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

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

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for _ in range(num):
	l = z()
	ans = 0
	for i in range(10):
		for j in range(10):
			t = str(i)
			cnt = 0
			for k in l:
				if k == t:
					cnt += 1
					if t == str(j):
						t = str(i)
					else:
						t = str(j)
			if cnt & 1 and i != j:
				cnt -= 1
			ans = max(ans, cnt)
	print(len(l) - ans)


def fu(b):
	c = 0
	j = 0
	for i in range(n):
		if a[i] == b[j]:
			c += 1
			j = (j + 1) % 2
	if len(set(b)) == 1:
		return n - c
	return n - c + j
t = int(input())
for _ in range(t):
	a = input()
	n = len(a)
	d = list(set(a))
	c = []
	for i in range(len(d)):
		for j in range(len(d)):
			c.append(fu(str(d[i]) + str(d[j])))
	print(min(c))


from collections import defaultdict
from itertools import combinations

def solve(s):
	n = len(s)
	if s[1:] + s[0] == s[n - 1] + s[:n - 1]:
		return 0
	d = defaultdict(int)
	maxi = 0
	for i in s:
		d[i] += 1
		maxi = max(maxi, d[i])
	if maxi == 1:
		return n - 2
	else:
		m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
		d = list(combinations(m, 2))
		for (i, j) in d:
			k = 0
			z = 0
			while k < n:
				if z % 2 == 0 and s[k] == str(i):
					z += 1
				elif z % 2 == 1 and s[k] == str(j):
					z += 1
				k += 1
			if z % 2 == 1:
				z -= 1
			maxi = max(maxi, z)
			k = 0
			z = 0
			while k < n:
				if z % 2 == 0 and s[k] == str(j):
					z += 1
				elif z % 2 == 1 and s[k] == str(i):
					z += 1
				k += 1
			if z % 2 == 1:
				z -= 1
			maxi = max(maxi, z)
		return n - maxi
t = int(input())
for _ in range(t):
	s = input()
	print(solve(s))


from sys import stdin
input = stdin.readline

def help():
	stri = list(input().strip())
	n = len(stri)
	if n <= 2:
		print(0)
		return
	seti = list(set(stri))
	ans = 0
	for i in range(10):
		ans = max(ans, max(stri.count(str(i)), ans))
	for a in seti:
		for b in seti:
			if a == b:
				continue
			cnt = 0
			for i in range(n):
				if stri[i] == a and cnt % 2 == 0:
					cnt += 1
				elif stri[i] == b and cnt % 2 == 1:
					cnt += 1
			cnt = cnt - cnt % 2
			ans = max(ans, cnt)
	print(n - ans)
for _ in range(int(input())):
	help()


from bisect import bisect_right
n = int(input())
inp = []
rum = []
for i in range(0, n):
	k = input()
	lis = []
	for _ in range(0, 10):
		lis.append([])
	for j in range(0, len(k)):
		lis[int(k[j])].append(j)
	ans = 0
	for a in range(0, 10):
		for b in range(0, 10):
			out = 0
			if len(lis[a]) == 0 or len(lis[b]) == 0:
				pass
			elif a == b:
				if ans < len(lis[a]):
					ans = len(lis[a])
			else:
				x = 0
				y = 0
				flag = 1
				out = 0
				pre = -1
				while flag:
					x = bisect_right(lis[a], pre)
					if x == len(lis[a]):
						flag = 0
						continue
					else:
						pre = lis[a][x]
					y = bisect_right(lis[b], pre)
					if y == len(lis[b]):
						flag = 0
						continue
					else:
						pre = lis[b][y]
					out = out + 2
				if ans < out:
					ans = out
	print(len(k) - ans)


for _ in range(int(input())):
	s = input()
	a = [0] * 10
	n = len(s)
	for i in range(n):
		a[ord(s[i]) - ord('0')] += 1
	ma = 0
	y = 0
	flag = 0
	for i in range(10):
		for j in range(10):
			flag = 0
			y = 0
			for k in range(n):
				if y == 0 and i == ord(s[k]) - ord('0'):
					y = 1
				elif j == ord(s[k]) - ord('0') and y == 1:
					y = 0
					flag += 2
			ma = max(ma, flag)
	for i in range(10):
		ma = max(ma, a[i])
	print(n - ma)


for _ in range(int(input())):
	s = input()
	f = {}
	for i in range(len(s)):
		if int(s[i]) not in f:
			f[int(s[i])] = 1
		else:
			f[int(s[i])] += 1
	m = max(f.values())
	t = len(f)
	(c, a) = (0, 0)
	if m == 1:
		print(len(s) - 2)
	elif m == len(s):
		print(0)
	else:
		l = len(s)
		for i in range(10):
			for j in range(10):
				f = 1
				for p in range(l):
					if int(s[p]) == i and f == 1:
						c += 1
						f = 0
					elif int(s[p]) == j and f == 0:
						c += 1
						f = 1
				if i != j and c % 2 == 1:
					c -= 1
				a = max(a, c)
				c = 0
		print(l - a)


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range
R = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

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

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def Ra():
	return map(int, open(0).read().split())

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()

class UnionFind:

	def __init__(self, n):
		self.table = [-1] * n

	def _root(self, x):
		if self.table[x] < 0:
			return x
		else:
			self.table[x] = self._root(self.table[x])
			return self.table[x]

	def find(self, x, y):
		return self._root(x) == self._root(y)

	def union(self, x, y):
		r1 = self._root(x)
		r2 = self._root(y)
		if r1 == r2:
			return
		d1 = self.table[r1]
		d2 = self.table[r2]
		if d1 <= d2:
			self.table[r2] = r1
			if d1 == d2:
				self.table[r1] -= 1
		else:
			self.table[r1] = r2

	def __str__(self):
		rt = [i if j < 0 else j for (i, j) in enumerate(self.table)]
		return str(rt)
show_flg = False
show_flg = True
ans = 0
t = I()
for _ in range(t):
	a = [int(i) for i in input()]
	ans = 0
	for i in range(10):
		for j in range(10):
			t = 0
			tmp = 0
			for x in a:
				if x == [i, j][t]:
					tmp += 1
					t = 1 - t
			if i != j:
				tmp = tmp // 2 * 2
			ans = max(ans, tmp - 0 * (tmp % 2) * (i != j) * 0)
	print(len(a) - ans)


from collections import Counter
import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

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

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
for _ in range(II()):
	aa = [int(c) for c in SI()]
	ac = Counter(aa)
	ans = max(ac.values())
	for f in range(10):
		pi = -1
		cnt = [0] * 10
		ppi = [-1] * 10
		for (i, a) in enumerate(aa):
			if a == f:
				pi = i
			elif ppi[a] != pi:
				cnt[a] += 1
				ppi[a] = pi
		ans = max(ans, max(cnt) * 2)
	print(len(aa) - ans)


def ct(s, a, b):
	tm = [a, b]
	id = 0
	res = 0
	for n in s:
		if n == tm[id]:
			res += 1
			id ^= 1
	if res % 2 and a != b:
		res -= 1
	return len(s) - res

def solv():
	s = list(map(int, input()))
	res = 10 ** 10
	p = 0
	q = 0
	for n in range(10):
		for k in range(10):
			v = ct(s, n, k)
			if v < res:
				res = v
				p = n
				q = k
	print(res)
for _ in range(int(input())):
	solv()


n = int(input())
for _ in range(n):
	s = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			temp = 0
			curr = i
			for ch in s:
				if int(ch) == curr:
					temp += 1
					if curr == i:
						curr = j
					else:
						curr = i
			if i != j and temp % 2 == 1:
				temp -= 1
			ans = max(ans, temp)
	print(len(s) - ans)


t = int(input())

def func(s, j, k):
	c = 0
	if j == k:
		for b in s:
			if int(b) != j:
				c += 1
	else:
		v = 0
		for b in s:
			if v == 0:
				if int(b) != j:
					c += 1
				else:
					v = (v + 1) % 2
			elif int(b) != k:
				c += 1
			else:
				v = (v + 1) % 2
		if v == 1:
			c += 1
	return c
for i in range(t):
	s = input()
	m = len(s)
	for j in range(10):
		for k in range(10):
			m = min(m, func(s, j, k))
	print(m)


for _ in range(int(input())):
	s = input()
	f = [0 for _ in range(10)]
	for c in s:
		f[int(c)] += 1
	ans = len(s) - max(f)
	for i in range(9):
		for j in range(i + 1, 10):
			am = False
			bm = -1
			an = 0
			(x, y) = (-1, -1)
			for c in s:
				if not am and (c == str(i) or c == str(j)):
					if c == str(i):
						(x, y) = (i, j)
					else:
						(x, y) = (j, i)
					am = True
					bm = 1
					continue
				if am:
					if bm == 1:
						if c == str(y):
							bm = 0
							an += 1
							continue
					if bm == 0:
						if c == str(x):
							bm = 1
							continue
			ans = min(ans, len(s) - 2 * an)
	print(ans)


def solve(stt):
	leni = len(stt)
	ls = list(stt)
	maxi = -1
	for i in range(0, 10):
		for j in range(0, 10):
			cr = str(i) + str(j)
			newcr = cr * (leni // 2)
			if leni % 2 == 1:
				newcr = newcr + str(i)
			lss = list(newcr)
			ans = 0
			k1 = 0
			k2 = 0
			while k1 < leni:
				if ls[k1] == lss[k2]:
					k1 += 1
					k2 += 1
					ans += 1
				else:
					k1 += 1
			if i != j and ans % 2 == 1:
				ans = -1
			maxi = max(maxi, ans)
	return leni - maxi
for i in range(int(input())):
	s = input()
	print(solve(s))


import math
import time
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from queue import PriorityQueue
import sys

def find(fi, se, s):
	toremove = 0
	cf = 0
	cs = 0
	for i in s:
		if cf == cs:
			if i == fi:
				cf += 1
			else:
				toremove += 1
		elif i == se:
			cs += 1
		else:
			toremove += 1
	if cf != cs and fi != se:
		toremove += 1
	return toremove
t = int(input())
for _ in range(t):
	s = input()
	ans = math.inf
	for fi in range(10):
		for se in range(10):
			ans = min(ans, find(str(fi), str(se), s))
	print(ans)


import sys
from collections import Counter

def func(s):
	s = list(s)
	hash = Counter(s)
	res = sys.maxsize
	for i in hash:
		res = min(res, len(s) - hash[i])
	for i in range(10):
		for j in range(10):
			if i != j:
				(f, e) = (str(i), str(j))
				curr = f
				count = 0
				for k in s:
					if k == curr:
						count += 1
						if curr == e:
							curr = f
						else:
							curr = e
				count = count // 2 * 2
				res = min(res, len(s) - count)
	return res
t = int(input())
for i in range(t):
	s = input()
	print(func(s))


import sys
import os
from io import BytesIO, IOBase

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

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

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

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

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def ddi():
	return defaultdict(int)

def ddl():
	return defaultdict(list)

def ddd():
	return defaultdict(defaultdict(int))
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')
from collections import defaultdict
from collections import deque
from math import gcd, pi
from bisect import bisect_left as bl
from bisect import bisect_right as br

def solve(s, i, j):
	res = 0
	for ch in s:
		if ch == i:
			res += 1
			(i, j) = (j, i)
	if i == j:
		return res
	if res & 1:
		return res - 1
	else:
		return res
for _ in range(ii()):
	s = input()
	n = len(s)
	mx = 0
	for i in range(10):
		for j in range(10):
			mx = max(mx, solve(s, str(i), str(j)))
	print(n - mx)


from collections import Counter

def solve(s):
	if len(s) <= 2:
		return 0
	c = Counter(s)
	if len(c) == 1:
		return 0
	ans = 100000000
	n = len(s)
	for i in range(10):
		for j in range(10):
			t = 0
			count = 0
			for x in s:
				if int(x) == i and t == 0:
					t += 1
					t %= 2
					count += 1
				elif int(x) == j and t == 1:
					t += 1
					t %= 2
					count += 1
			if count % 2 == 1 and i != j:
				count -= 1
			ans = min(ans, n - count)
	return ans
t = int(input())
for we in range(t):
	s = list(input())
	print(solve(s))


from collections import defaultdict
con = 10 ** 9 + 7
INF = float('inf')

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

def main():
	T = int(input())
	for _ in range(T):
		s = list(map(int, list(input())))
		N = len(s)
		ans = N
		for i in range(10):
			for j in range(10):
				cnt = 0
				for k in s:
					if cnt % 2 == 0 and k == i:
						cnt += 1
					elif cnt % 2 == 1 and k == j:
						cnt += 1
				if i != j:
					cnt = int(cnt // 2) * 2
				ans = min(ans, N - cnt)
		if N == 1:
			ans = 0
		print(ans)
main()


for _ in range(0, int(input())):
	l = list(input())
	d = {}
	for i in range(0, len(l)):
		if int(l[i]) in d:
			d[int(l[i])].append(i)
		else:
			d.update({int(l[i]): [i]})
	odd_res = 0
	even_res = 999999999
	for i in d:
		odd_res = max(len(d[i]), odd_res)
	odd_res = len(l) - odd_res
	if odd_res == len(l) - 1:
		odd_res -= 1
	for i in range(0, 10):
		for j in range(0, 10):
			if i != j:
				temp = []
				for m in range(0, len(l)):
					if int(l[m]) in [i, j]:
						if temp != [] and temp[-1] == l[m]:
							pass
						else:
							temp.append(l[m])
				if temp != []:
					flag5 = 0
					tem = 0
					for m in range(0, len(temp) - 1):
						if temp[m] == temp[m + 1]:
							tem += 1
					if flag5 == 0:
						if len(temp) % 2 == 0:
							even_res = min(even_res, len(l) - len(temp))
						else:
							even_res = min(even_res, len(l) - len(temp) + 1)
	print(min(odd_res, even_res))


T = int(input())
for t in range(T):
	s = input()
	mx = 0
	arr = []
	for i in range(10):
		arr.append([])
	cnt = 0
	for k in s:
		arr[int(k)].append(cnt)
		cnt += 1
	for i in range(9):
		for j in range(i + 1, 10):
			odd = 0
			even = 0
			(m, n) = (0, 0)
			ans = 0
			for k in range(len(arr[i]) + len(arr[j])):
				if m == len(arr[i]) or n == len(arr[j]):
					break
				if arr[i][m] < arr[j][n]:
					even = 0
					m += 1
					if odd == 0:
						ans += 1
						odd = 1
				else:
					odd = 0
					n += 1
					if even == 0:
						ans += 1
						even = 1
			if len(arr[i]) != 0 and len(arr[j]) != 0:
				if arr[i][-1] > arr[j][-1] and arr[i][0] > arr[j][0] or (arr[i][-1] < arr[j][-1] and arr[i][0] < arr[j][0]):
					ans += ans % 2
				else:
					ans -= ans % 2
			mx = max(mx, ans)
	for i in range(10):
		mx = max(mx, len(arr[i]))
	print(len(s) - mx)


t = int(input())
for _ in range(t):
	list1 = list(map(int, input()))
	max_count = 0
	for i in range(10):
		temp = list1.count(i)
		if temp > max_count:
			max_count = temp
	ans = 0
	for i in range(10):
		for j in range(10):
			temp1 = i
			temp2 = j
			search = i
			count = 0
			for val in list1:
				if val == search:
					if search == i:
						search = j
					else:
						search = i
						count += 1
			if count > ans:
				ans = count
	print(min(len(list1) - 2 * ans, len(list1) - max_count))


import math
t = int(input())

def two(x, y):
	ans = 0
	for i in range(n):
		if ans % 2 == 1:
			if a[i] == y:
				ans += 1
		elif a[i] == x:
			ans += 1
	if ans % 2 == 1:
		ans -= 1
	return ans
for tt in range(t):
	a = list(map(int, input()))
	n = len(a)
	ans = 0
	for i in range(10):
		for j in range(10):
			if i != j:
				ans = max(ans, two(i, j))
	for i in range(10):
		tem = 0
		for y in range(n):
			if a[y] == i:
				tem += 1
		ans = max(ans, tem)
	print(n - ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

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

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

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	s = data()
	if len(set(s)) == 1 or len(s) <= 2:
		out(0)
		continue
	c = dd(list)
	for i in range(len(s)):
		c[int(s[i])].append(i)
	answer = len(s) - 2
	for i in c.values():
		answer = min(answer, len(s) - len(i))
	for c1 in range(10):
		if not c[c1]:
			continue
		for c2 in range(10):
			if c1 == c2 or not c[c2]:
				continue
			t1 = t2 = cnt = 0
			(a, b) = (c[c1], c[c2])
			par = 0
			while t1 < len(a) and t2 < len(b):
				if par:
					if a[t1] < b[t2]:
						t1 += 1
						par = 0
						cnt += 1
					else:
						t2 += 1
				elif b[t2] < a[t1]:
					t2 += 1
					par = 1
					cnt += 1
				else:
					t1 += 1
			if par and t1 < len(a):
				if a[t1] > b[-1]:
					cnt += 1
			if not par and t2 < len(b):
				if b[t2] > a[-1]:
					cnt += 1
			if cnt & 1:
				cnt -= 1
			answer = min(answer, len(s) - cnt)
	out(answer)


import sys
input = sys.stdin.readline
t = int(input())
for r in range(t):
	s = input().strip('\n')
	n = len(s)
	d = {}
	for i in s:
		try:
			d[i] += 1
		except:
			d[i] = 1
	if len(d) == n:
		print(n - 2)
	elif len(d) == 1:
		print(0)
	else:
		mini = 9999999999999999999999999
		for i in range(0, 10):
			for j in range(0, 10):
				counter = 0
				toggle = 0
				for k in range(n):
					if toggle == 0 and s[k] == str(i):
						toggle ^= 1
					elif toggle == 1 and s[k] == str(j):
						toggle ^= 1
					else:
						counter += 1
				if i != j and (len(s) - counter) % 2 == 1:
					counter += 1
				mini = min(mini, counter)
		print(mini)


from sys import stdin
from collections import defaultdict
input = stdin.readline
t = int(input())
for _ in range(t):
	s = input().rstrip()
	bestdelt = 10000000000.0
	for k in range(10):
		for l in range(10):
			req = (str(k), str(l))
			delt = 0
			i = 0
			while i < len(s):
				if s[i] == req[0]:
					j = i + 1
					while j < len(s) and s[j] != req[1]:
						j += 1
					if j < len(s):
						delt += j - i - 1
					elif req[0] == req[1] == s[i]:
						delt += j - i - 1
					else:
						delt += j - i
					i = j + 1
				else:
					delt += 1
					i += 1
			bestdelt = min(bestdelt, delt)
	print(bestdelt)


from sys import stdin
from collections import Counter

def main():
	input = stdin.readline
	for t in range(int(input())):
		s = input().rstrip()
		n = len(s)
		b = Counter()
		ans = 0
		for i in range(10):
			for j in range(10):
				l = k = ma = 0
				while k < n:
					if i == 0 and j == 0:
						b[s[k]] += 1
						ans = max(ans, b[s[k]])
					if l == 0:
						if int(s[k]) == i:
							l = 1
					elif int(s[k]) == j:
						ma = ma + 2
						l = 0
					k += 1
				ans = max(ans, ma)
		print(n - ans)
main()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
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')
for t in range(int(input())):
	s = input()
	mx = 2
	curr = 0
	n = len(s)
	for i in range(10):
		for j in range(10):
			c = 0
			curr = 0
			for k in range(n):
				if c == 0:
					if str(s[k]) == str(i):
						c = 1
						curr += 1
				elif str(s[k]) == str(j):
					c = 0
					curr += 1
			if curr % 2 == 1 and i != j:
				curr -= 1
			mx = max(mx, curr)
	r = n - mx
	print(r)


t = int(input())
for i in range(t):
	stro = input()
	cntm = 0
	for too in range(10):
		for ga in range(10):
			if too != ga:
				f = 0
				cnt = 0
				for c in stro:
					if f == 0 and int(c) == too:
						cnt += 1
						f = 1
					elif f == 1 and int(c) == ga:
						cnt += 1
						f = 0
				if cnt % 2 != 0:
					cnt -= 1
			else:
				cnt = stro.count(str(too))
			if cnt > cntm:
				cntm = cnt
	print(len(stro) - cntm)


from sys import stdin
for _ in range(int(input())):
	a = stdin.readline().rstrip()
	d = {}
	le = len(a)
	for i in range(le):
		x = d.get(a[i], 0)
		if x:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	d = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
	m = max(d.values())
	done = []
	for (i, j) in d.items():
		for (k, l) in d.items():
			if i != k and i + k not in done:
				done.append(i + k)
				done.append(k + i)
				if min([j, l]) * 2 > m:
					start = []
					for test in range(le):
						if not start:
							if a[test] in [i, k]:
								start.append(a[test])
						elif start[-1] != a[test] and a[test] in [i, k]:
							start.append(a[test])
					if len(start) > m:
						if start[0] == start[-1]:
							m = len(start) - 1
						else:
							m = len(start)
	print(le - m)


from math import *
from collections import *
from random import *
from bisect import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	s = input().rstrip('\n')
	f = Counter(s)
	x = len(s)
	r = float('inf')
	if len(f) == 1:
		print(0)
		continue
	d = {i: [] for i in range(10)}
	for i in range(len(s)):
		try:
			d[int(s[i])].append(i)
		except:
			d[s[i]] = [i]
	for i in range(10):
		for j in range(10):
			if i == j:
				r = min(r, len(s) - len(d[i]))
				continue
			c = 1
			(x, y) = (0, 0)
			try:
				fi = d[i][0]
			except:
				continue
			tu = 0
			while x < len(d[i]) or y < len(d[j]):
				if tu % 2 ^ 1:
					if y >= len(d[j]):
						break
					if d[j][y] > fi:
						c += 1
						y += 1
						se = d[j][y - 1]
						tu += 1
					else:
						y += 1
						continue
				else:
					if x >= len(d[i]):
						break
					if d[i][x] > se:
						c += 1
						tu += 1
						x += 1
						fi = d[i][x - 1]
					else:
						x += 1
						continue
			r = min(r, len(s) - (c - c % 2))
	print(r)


for _ in range(int(input())):
	napis = input()
	count = [[0 for _ in range(10)] for _ in range(10)]
	for x in napis:
		d = int(x)
		for p in range(10):
			count[d][p] = count[p][d] + 1
	print(len(napis) - max(max([max(i) for i in count]) // 2 * 2, max([count[i][i] for i in range(10)])))


for _ in range(int(input())):
	s = input()
	o = max((s.count(i) for i in {*s}))
	l = [[0 for i in range(10)] for i in range(10)]
	for i in '0123456789':
		k = 0
		q = {}
		for m in range(10):
			q[m] = set()
		for j in s:
			if j == i:
				k += 1
			elif k not in q[int(j)] and k > 0:
				l[int(i)][int(j)] += 1
				q[int(j)].add(k)
	p = 0
	for i in l:
		p = max(p, max(i))
	print(len(s) - max(p * 2, o))


t = int(input())

def min_erase(c, s):
	erase = 0
	t = 0
	for d in s:
		if d == c[t]:
			t ^= 1
		else:
			erase += 1
	if c[0] != c[1] and t == 1:
		erase += 1
	return erase
for _ in range(t):
	s = input()
	ans = len(s)
	for x in range(10):
		for y in range(10):
			c = [str(x), str(y)]
			cur = min_erase(c, s)
			ans = min(ans, cur)
	print(ans)


t = int(input())
for _ in range(0, t):
	s = input()

	def test(arr, phase):
		ret = 0
		iphase = phase
		for c in s:
			if arr[phase] != int(c):
				ret += 1
			else:
				phase ^= 1
		if iphase != phase and arr[0] != arr[1]:
			ret += 1
		return ret
	ret = 100000000
	for i in range(0, 10):
		for j in range(0, 10):
			ret = min(ret, test([i, j], 0))
	print(ret)


for _ in range(int(input())):
	S = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			c = str(i)
			l = 0
			for k in S:
				if k == c:
					l += 1
					if c == str(j):
						c = str(i)
					else:
						c = str(j)
			if l % 2 and i != j:
				l -= 1
			ans = max(ans, l)
	print(len(S) - ans)


from math import sqrt
for _ in range(int(input())):
	s = input()
	index = [[] for i in range(10)]
	present = [[0 for j in range(len(s))] for i in range(10)]
	for i in range(len(s)):
		if i != 0:
			for j in range(10):
				present[j][i] += present[j][i - 1]
		present[int(s[i])][i] += 1
	maxx = 0
	for i in present:
		maxx = max(maxx, i[-1])
	for i in range(len(s)):
		index[int(s[i])].append(i)
	final = 0
	ind1 = 0
	ind2 = 0
	for i in range(len(index)):
		other = [0] * 10
		for j in range(1, len(index[i])):
			one = index[i][j - 1]
			two = index[i][j]
			for k in range(10):
				if present[k][two] - present[k][one] != 0 and k != i:
					other[k] += 1
		for j in range(10):
			if len(index[i]) != 0 and j != i and (present[j][-1] - present[j][index[i][-1]] >= 1):
				other[j] += 1
			elif j != i and len(index[i]) != 0 and (present[j][index[i][0]] - present[j][0] >= 1):
				other[j] += 1
			elif len(index[i]) != 0 and index[i][0] != 0 and (present[j][0] == 1):
				other[j] += 1
		total = max(other)
		if total > final:
			final = total
	ava = 2 * final
	if maxx > ava:
		ava = maxx
	print(len(s) - ava)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	s = input()
	s = s[0:len(s) - 1]
	costs = [0] * 10
	for i in range(10):
		costs[i] = [0] * 10
	isf = [0] * 10
	for i in range(10):
		isf[i] = [True] * 10
	for c in s:
		c = int(c)
		for i in range(10):
			for j in range(10):
				if isf[i][j]:
					if c == i:
						isf[i][j] = False
					else:
						costs[i][j] += 1
				elif c == j:
					isf[i][j] = True
				else:
					costs[i][j] += 1
	mincost = 10000000000000000000000000000
	for i in range(10):
		for j in range(10):
			if not isf[i][j] and i != j:
				costs[i][j] += 1
			mincost = min(mincost, costs[i][j])
	print(mincost)


from collections import defaultdict
import math

def solve(a):
	if len(a) <= 2:
		return 0
	result = float('inf')
	for i in '0123456789':
		for j in '0123456789':
			first = i
			second = j
			f = True
			s = False
			n = 0
			for elements in a:
				if first == elements and f:
					n += 1
					f = False
					s = True
				elif second == elements and s:
					n += 1
					f = True
					s = False
			if first != second and n % 2 == 1:
				n -= 1
			result = min(len(a) - n, result)
	return result
for _ in range(int(input())):
	a = input()
	print(solve(a))


t = int(input())
for _ in range(t):
	s = input()
	l = [0] * 10
	for i in range(10):
		l[i] = s.count(str(i))
	minans = len(s) - max(l)
	ans = -1
	for i in range(10):
		if s.find(str(i)) != -1:
			last = s.find(str(i))
			ll = last
			for j in range(10):
				last = ll
				kol = 0
				if s.find(str(j), last + 1) != -1:
					kol = 2
					last = s.find(str(j), last + 1)
					ok = True
					while ok:
						if s.find(str(i), last + 1) != -1:
							last = s.find(str(i), last + 1)
							if s.find(str(j), last + 1) != -1:
								last = s.find(str(j), last + 1)
								kol += 2
							else:
								ok = False
						else:
							ok = False
				ans = max(ans, kol)
	print(min(minans, len(s) - ans))


t = int(input())
for t1 in range(0, t):
	s = input()
	n = len(s)
	ans = n
	p = '0123456789'
	for i in p:
		for j in p:
			if i == j:
				continue
			f = 0
			c = 0
			for k in s:
				if k == i and f == 0:
					c = c + 1
					f = 1
				elif k == j and f == 1:
					c = c + 1
					f = 0
			c = c // 2 * 2
			ans = min(ans, n - c)
	for i in p:
		ans = min(ans, n - s.count(i))
	print(ans)


for _ in range(int(input())):
	s = input()
	n = len(s)
	a = [0 for i in range(10)]
	m = 0
	for i in s:
		a[int(i)] += 1
		m = max(m, a[int(i)])
	maxx = 0
	for i in range(10):
		if a[i] > 0:
			for j in range(10):
				if a[j] > 0:
					if i == j:
						continue
					sl = str(i) + str(j)
					ind = 0
					p = 0
					le = 0
					while p < n:
						if s[p] == sl[ind]:
							le += 1
							ind = (ind + 1) % 2
							while s[p] != sl[ind]:
								p += 1
								if p == n:
									break
						else:
							p += 1
					if le % 2 != 0:
						le -= 1
					maxx = max(maxx, le)
	print(min(n - m, n - maxx))


import sys
input = sys.stdin.readline

def rle(lst):
	ans = []
	cnt = 1
	ini = lst[0]
	for i in range(1, len(lst)):
		if ini == lst[i]:
			cnt += 1
		else:
			ans.append((ini, cnt))
			cnt = 1
			ini = lst[i]
	ans.append((ini, cnt))
	return ans
t = int(input())
for _ in range(t):
	s = list(input())[:-1]
	ans = len(s)
	for i in range(10):
		for j in range(i, 10):
			now = []
			for k in range(len(s)):
				if s[k] == str(i) or s[k] == str(j):
					now.append(s[k])
			if len(now) == 0:
				pass
			else:
				u = rle(now)
				if len(u) == 1:
					ans = min(ans, len(s) - len(now))
				elif len(u) % 2 == 0:
					ans = min(ans, len(s) - len(u))
				else:
					ans = min(ans, len(s) - len(u) + 1)
	print(ans)


def main():
	t = int(input())
	from collections import Counter
	for _ in range(t):
		s = str(input())
		n = len(s)
		for i in range(n):
			if s[i] != s[0]:
				break
		else:
			print(0)
			continue
		ans = 10 ** 18
		for i in range(10):
			for j in range(10):
				temp = []
				for k in range(n):
					if len(temp) % 2 == 0:
						if s[k] == str(i):
							temp.append(s[k])
					elif s[k] == str(j):
						temp.append(s[k])
				if len(temp) != 0:
					if len(temp) % 2 == 1:
						ans = min(ans, n - len(temp) + 1)
					else:
						ans = min(ans, n - len(temp))
		C = Counter(s)
		X = list(C.items())
		X.sort(key=lambda x: -x[1])
		if X[0][1] % 2 == 0:
			p = X[0][1] - 1
			ans = min(ans, n - p)
		else:
			p = X[0][1]
			ans = min(ans, n - p)
		print(ans)
main()


T = int(input())
while T:
	s = input()
	D = {}
	for i in range(len(s)):
		if int(s[i]) in D:
			D[int(s[i])].append(i)
		else:
			D[int(s[i])] = [i]
	m = 0
	for i in D:
		m = max(m, len(D[i]))
	for i in D:
		for j in D:
			if i != j:
				a = 1
				b = 0
				Z = []
				x = D[i][0]
				Z.append(x)
				while a < len(D[i]) + 1 and b < len(D[j]) and (x < len(s)):
					while b < len(D[j]) and D[j][b] < x:
						b = b + 1
					if b < len(D[j]):
						x = D[j][b]
						Z.append(x)
					else:
						x = len(s) + 1
					while a < len(D[i]) and D[i][a] < x:
						a = a + 1
					if a < len(D[i]):
						x = D[i][a]
						Z.append(x)
					else:
						x = len(s) + 1
				m = max(m, len(Z) - len(Z) % 2)
	print(len(s) - m)
	T = T - 1


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')

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))
from collections import defaultdict as dc
for _ in range(N()):
	s = input()
	s = [int(c) for c in s]
	dic = dc(list)
	for i in range(len(s)):
		dic[s[i]].append(i)
	res = max((len(dic[i]) for i in range(10)))
	for a in range(9):
		if len(dic[a]) * 2 <= res:
			continue
		for b in range(a + 1, 10):
			if len(dic[b]) * 2 <= res:
				continue
			tmp = 0
			if dic[a][0] > dic[b][0]:
				(m, n) = (b, a)
			else:
				(m, n) = (a, b)
			(i, j) = (0, 0)
			while i < len(dic[m]) and j < len(dic[n]):
				tmp += 1
				while i < len(dic[m]) and dic[m][i] < dic[n][j]:
					i += 1
				if i >= len(dic[m]):
					break
				while j < len(dic[n]) and dic[n][j] < dic[m][i]:
					j += 1
			res = max(res, tmp * 2)
	print(len(s) - res)


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

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 swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(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
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	s = input().strip()
	n = len(s)
	dick = {}
	ans = INF
	for i in s:
		dick[i] = dick.get(i, 0) + 1
	mx = NINF
	for i in dick:
		mx = max(mx, dick[i])
	this = n - mx
	ans = min(ans, this)
	if len(dick) > 1:
		ans = min(ans, n - 2)
	for i in range(10):
		for j in range(i + 1, 10):
			this = []
			for x in s:
				if x == str(i) or x == str(j):
					this.append(x)
			p = 0
			prev = str(j)
			for x in this:
				if x != prev:
					p += 1
					prev = x
			t = p // 2
			p = 0
			prev = str(i)
			for x in this:
				if x != prev:
					p += 1
					prev = x
			p = max(p // 2, t)
			ans = min(ans, n - 2 * p)
	print(ans)


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	s = input()
	n = len(s)
	ma = 0
	mi = 10
	for j in s:
		ma = max(ma, int(j))
		mi = min(mi, int(j))
	ans = 0
	for j in range(mi, ma + 1):
		for k in range(mi, ma + 1):
			if j == k:
				c = s.count(str(j))
			else:
				c = 0
				flag = 0
				for ch in s:
					if flag == 0 and int(ch) == j:
						flag = 1
					elif flag == 1 and int(ch) == k:
						flag = 0
						c += 2
			ans = max(ans, c)
	print(n - ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(S):
	N = len(S)
	chains = defaultdict(int)
	for x in S:
		nextChains = defaultdict(int)
		for d in range(10):
			if d != x:
				nextChains[d, x] = chains[x, d] + 1
		for (tup, v) in chains.items():
			nextChains[tup] = max(nextChains[tup], v)
		chains = nextChains
	longest = max(Counter(S).values())
	longest = max(longest, max((v // 2 * 2 for v in chains.values())))
	return N - longest
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	S = [int(c) for c in input().decode().rstrip()]
	ans = solve(S)
	print(ans)


def answer(A):
	d = {}
	for i in A:
		if i not in d:
			d[i] = 1
		else:
			d[i] += 1
	maxi = max(d.values())
	for i in range(0, 10):
		for j in range(0, 10):
			if i != j:
				count = 0
				search = str(i)
				for k in range(len(A)):
					if A[k] == search:
						if search == str(i):
							search = str(j)
						else:
							search = str(i)
						count += 1
				maxi = max(maxi, count - count % 2)
	return len(A) - maxi
t = int(input())
for i in range(t):
	s = input()
	print(answer(s))


from collections import deque
t = int(input())
for _ in range(t):
	s = list(input())
	maxcnt1 = 0
	maxcnt2 = 0
	n = len(s)
	for i in range(10):
		a = 0
		cnt = 0
		x = [0] * 10
		for j in s:
			if int(j) == i:
				if a == 1:
					for k in range(10):
						x[k] += y[k]
				a = 1
				cnt += 1
				y = [0] * 10
			elif a == 1:
				y[int(j)] = 1
		if a == 1:
			for k in range(10):
				x[k] += y[k]
		maxcnt1 = max(cnt, maxcnt1)
		maxcnt2 = max(max(x), maxcnt2)
	ans = min(n - maxcnt1, n - 2 * maxcnt2)
	print(ans)


import sys
input = sys.stdin.readline
inf = int(10000000000.0)
t = int(input())
while t:
	t -= 1
	s = input().strip()
	n = len(s)
	d = dict()
	for i in s:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	m1 = max(d.values())
	m2 = 0
	for i in range(10):
		for j in range(10):
			if i != j:
				f = 0
				l = 0
				for k in s:
					if f == 0 and k == str(i):
						f = 1
						l += 1
					elif f == 1 and k == str(j):
						f = 0
						l += 1
				m2 = max(l, m2)
	print(n - max(m1, m2 >> 1 << 1))


def do(s, x, y):
	cnt = 0
	for c in s:
		if int(c) == x:
			cnt += 1
			(x, y) = (y, x)
	if x != y and cnt % 2 == 1:
		cnt -= 1
	return cnt

def solve():
	s = input()
	res = 0
	for i in range(10):
		for j in range(10):
			res = max(res, do(s, i, j))
	print(len(s) - res)
tc = int(input())
for _ in range(tc):
	solve()


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
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')

def main():
	t = int(input())
	for i in range(t):
		s = str(input())
		d = [0] * 10
		d.append(2)
		for j in s:
			d[int(j)] += 1
		mn = min([len(s) - x for x in d])
		circle = []
		for j in range(10):
			for k in range(10):
				if j != k:
					circle.append(str(j) + str(k))
		for c in circle:
			cnt = 0
			index = 0
			while index < len(s):
				if s[index] == c[0]:
					cnt += 1
					temp = index
					while temp < len(s):
						if s[temp] == c[1]:
							cnt += 1
							break
						temp += 1
					index = temp
				else:
					index += 1
			mn = min(mn, len(s) - cnt // 2 * 2)
		print(mn)
main()


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

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

def IO():
	return 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 readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

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

def sieve():
	li = [True] * 1000001
	(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 = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

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

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

def solve(i):
	s = input()
	n = len(s)
	ans = 10000000.0
	for i in range(10):
		for j in range(10):
			(findi, findj) = (True, False)
			count = 0
			(i, j) = (str(i), str(j))
			for k in range(n):
				if i == j and s[k] == i:
					count += 1
				else:
					if findi == True and s[k] == i:
						findi = False
						count += 1
						findj = True
					if findj == True and s[k] == j:
						findj = False
						count += 1
						findi = True
			if i == j:
				ans = min(ans, n - count)
			elif count % 2 == 0:
				ans = min(ans, n - count)
			else:
				ans = min(ans, n - (count - 1))
	P(ans)
	return
t = II()
for i in range(t):
	solve(i)


t = int(input())
for _ in range(t):
	A = str(input())
	A = list(A)
	A = [int(s) for s in A]
	ans = 10000007
	for i in range(10):
		for j in range(10):
			c = 0
			d = 0
			for k in range(len(A)):
				if c % 2 == 0:
					if A[k] == i:
						c += 1
					else:
						d += 1
				elif A[k] == j:
					c += 1
				else:
					d += 1
			if c % 2 == 0:
				ans = min(ans, d)
			elif i == j:
				ans = min(ans, d)
			else:
				ans = min(ans, d + 1)
	print(ans)


import os
import operator
import sys
import bisect
import _operator
from _collections import defaultdict
from io import BytesIO, IOBase

def inar():
	return [int(k) for k in input().split()]

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

def main():
	for _ in range(int(input())):
		st = input()
		dic = defaultdict(int)
		n = len(st)
		for i in range(len(st)):
			dic[st[i]] += 1
		ans = n - max(dic.values())
		for i in range(0, 10):
			for j in range(0, 10):
				ok = True
				count = 0
				for k in range(n):
					if ok:
						if st[k] == str(i):
							count += 1
							ok = False
					elif st[k] == str(j):
						count += 1
						ok = True
				if count % 2 != 0:
					count -= 1
				ans = min(ans, n - count)
		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
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	s = SI()
	n = len(s)
	ans = n - s.count(max('0123456789', key=lambda c: s.count(c)))
	for i in range(10):
		for j in range(10):
			val = 0
			p = str(i)
			for c in s:
				if c == str(j) and p == str(i) or (c == str(i) and p == str(j)):
					val += 1
					p = c
			if val % 2:
				val -= 1
			ans = min(ans, n - val)
	print(ans)


T = int(input())
for t in range(T):
	s = input()
	ans = len(s)
	for a in range(10):
		for b in range(10):
			reqd = [str(a), str(b)]
			cost = 0
			idx = 0
			for i in range(len(s)):
				if s[i] != reqd[idx]:
					cost += 1
				else:
					idx ^= 1
			if idx != 0 and a != b:
				cost += 1
			ans = min(cost, ans)
	print(ans)


import sys
INP = lambda : sys.stdin.readline().strip()
INT = lambda : int(INP())
MAP = lambda : map(int, INP().split())
ARR = lambda : [int(i) for i in INP()]

def JOIN(arr, x=' '):
	return x.join([str(i) for i in arr])

def EXIT(x='NO'):
	print(x)
	exit()

def do(f, arr, a, b):
	xx = 0
	for x in arr:
		if x == f:
			if x == a:
				f = b
			else:
				f = a
			xx += 1
	return xx // 2 * 2

def solve():
	arr = [int(x) for x in list(INP())]
	c = {x: 0 for x in arr}
	for x in arr:
		c[x] += 1
	cs = sorted(list(c.items()), key=lambda x: x[1], reverse=True)
	if len(cs) < 2:
		return 0
	ans = cs[0][1]
	l = len(cs)
	for i in range(l):
		for j in range(i + 1, l):
			ans = max(ans, do(cs[i][0], arr, cs[i][0], cs[j][0]))
			ans = max(ans, do(cs[j][0], arr, cs[i][0], cs[j][0]))
	return len(arr) - ans
for _ in range(INT()):
	print(solve())


for _ in range(int(input())):
	s = input()
	a = 0
	l = len(s)
	for i in range(10):
		for j in range(10):
			f = 1
			c = 0
			for p in range(l):
				if int(s[p]) == i and f == 1:
					c += 1
					f = 0
				elif int(s[p]) == j and f == 0:
					c += 1
					f = 1
			if i != j and c % 2 == 1:
				c -= 1
			a = max(a, c)
	print(l - a)


import sys
import itertools
from collections import defaultdict
readline = sys.stdin.buffer.readline

def even(n):
	return 1 if n % 2 == 0 else 0
lst = [chr(i) for i in range(ord('0'), ord('9') + 1)]

def main():
	s = readline().rstrip().decode('utf-8')
	dic1 = defaultdict(int)
	for i in s:
		dic1[i] += 1
	ans = max(list(dic1.values()))
	first = 0
	for itr in itertools.combinations(lst, 2):
		res = 0
		nec = -1
		for j in s:
			if nec == -1:
				if j == itr[0]:
					res += 1
					nec = 1
					first = 0
				elif j == itr[1]:
					res += 1
					nec = 0
					first = 1
			elif nec == 0:
				if j == itr[nec]:
					res += 1
					nec = 1
			elif nec == 1:
				if j == itr[nec]:
					res += 1
					nec = 0
		if first != nec:
			res -= 1
		ans = max(ans, res)
	print(len(s) - ans)
query = int(readline())
for _ in range(query):
	main()


def check(a, b, string):
	res = ''
	cnt = 0
	for s in string:
		if s == a or s == b:
			if s != res:
				cnt += 1
				res = s
	if cnt % 2:
		cnt -= 1
	return cnt

def main():
	string = str(input())
	if len(set(string)) == 1:
		print(0)
		return
	elif len(set(string)) == len(string):
		print(len(string) - 2)
		return
	arr = {}
	for x in string:
		if arr.get(x) == None:
			arr[x] = 1
		else:
			arr[x] += 1
	mx = -1
	for x in arr:
		mx = max(mx, arr[x])
	mn = -1
	for x in arr:
		for y in arr:
			if x != y:
				temp = check(x, y, string)
				temp2 = check(y, x, string)
				if max(temp, temp2) > mn:
					mn = max(temp, temp2)
	print(len(string) - max(mn, mx))
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


import math
n = int(input())
arr = []
for i in range(n):
	arr_c = []
	arr1 = [int(d) for d in list(input())]
	for j in range(0, 10):
		for k in range(0, 10):
			if j != k:
				coun = 0
				y = 0
				for t in range(len(arr1)):
					if coun == 0 and arr1[t] == j:
						coun += 1
						y = j
					elif coun == 0 and arr1[t] == k:
						coun += 1
						y = k
					elif arr1[t] == j and y == k:
						coun += 1
						y = j
					elif arr1[t] == k and y == j:
						coun += 1
						y = k
				if coun % 2 == 0:
					arr_c.append(coun)
				else:
					arr_c.append(coun - 1)
			elif j == k:
				coun = 0
				for t in range(len(arr1)):
					if arr1[t] == j:
						coun += 1
				arr_c.append(coun)
	arr.append(len(arr1) - max(arr_c))
for i in range(len(arr)):
	print(arr[i])


production = True
import sys, math, collections, bisect, itertools, heapq, decimal, random, copy, re

def input(f=0, m=0):
	if m > 0:
		return [input(f) for i in range(m)]
	else:
		l = sys.stdin.readline()[:-1]
		if f >= 10:
			u = False
			f = int(str(f)[-1])
		else:
			u = True
		if f == 0:
			p = [l]
		elif f == 1:
			p = list(map(int, l.split()))
		elif f == 2:
			p = list(map(float, l.split()))
		elif f == 3:
			p = list(l)
		elif f == 4:
			p = list(map(int, list(l)))
		elif f == 5:
			p = l.split()
		return p if u else p[0]

def out(l, f=0, n=True):
	if f == 0:
		p = str(l)
	elif f == 1:
		p = ' '.join(map(str, l))
	elif f == 2:
		p = '\n'.join(map(str, l))
	elif f == 3:
		p = ''.join(map(str, l))
	print(p, end='\n' if n else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c
ceil = lambda a, b: -(-a // b)
flip = lambda a: a + 1 & 1

def mapl(i, f=0):
	if f == 0:
		return list(map(int, i))
	elif f == 1:
		return list(map(str, i))
	elif f == 2:
		return list(map(list, i))

def solve():
	s = input(3)
	y = [list(str(i).zfill(2)) for i in range(100)]
	p = [str(i) for i in range(10)]
	m = 10 ** 9
	for i in p:
		c = 0
		for j in s:
			if j != i:
				c += 1
		m = min(m, c)
	for i in y:
		t = 0
		c = 0
		for j in s:
			if j != i[t]:
				c += 1
			else:
				t = flip(t)
		if t:
			c += 1
		m = min(m, c)
	log(s)
	out(m)
	return
for i in range(input(11)):
	solve()


def solution():
	s = list(input())
	ans = 0
	for i in range(10):
		for j in range(10):
			x = 0
			cnt = 0
			for k in s:
				if x == 0 and str(i) == k:
					x = 1 - x
					cnt += 1
				elif x == 1 and str(j) == k:
					x = 1 - x
					cnt += 1
			if cnt % 2 == 0 or i == j:
				ans = max(ans, cnt)
	print(len(s) - ans)
t = int(input())
for _ in range(t):
	solution()


t = int(input())
for _ in range(t):
	s = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			l = 0
			st = str(i)
			for k in s:
				if k == st:
					l += 1
					if st == str(j):
						st = str(i)
					else:
						st = str(j)
			if l % 2 == 1 and i != j:
				l -= 1
			ans = max(ans, l)
	print(len(s) - ans)


from sys import stdin
from collections import Counter
for _ in range(int(stdin.readline())):
	s = list(stdin.readline().strip())
	z = Counter(s)
	ans = 0
	for i in range(10):
		for j in range(10):
			if i == j:
				continue
			ans1 = val = 0
			for x in s:
				if not val and x == str(i):
					val = 1
				elif val and x == str(j):
					val = 0
					ans1 += 2
			ans = max(ans, ans1)
	print(min(len(s) - ans, len(s) - z[max(z, key=z.get)]))


def comb(a, x, y):
	flag = True
	count = 0
	for ele in a:
		if flag:
			if ele == x:
				flag = False
		elif ele == y:
			count += 1
			flag = True
	return len(a) - 2 * count
T = int(input())
for case in range(T):
	a = input()
	ans = float('inf')
	for i in range(0, 10):
		for j in range(0, 10):
			if i == j:
				continue
			else:
				ans = min(ans, comb(a, str(i), str(j)))
	for i in range(10):
		count = a.count(str(i))
		ans = min(ans, len(a) - count)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
profile = 0
pypy = 1

def iin():
	return int(input())

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

def main():
	T = iin()
	while T:
		T -= 1
		s = list(map(int, list(input())))
		ans = len(s)
		n = len(s)
		dc = {i: [] for i in range(10)}
		for (i, j) in enumerate(s):
			dc[j].append(i)
		for i in range(10):
			ans = min(ans, n - len(dc[i]))
		for i in range(10):
			for j in range(i + 1, 10):
				if dc[i] and dc[j]:
					ch = 0
					(x1, x2) = (0, 0)
					(l1, l2) = (len(dc[i]), len(dc[j]))
					(a1, a2) = (dc[i], dc[j])
					pv = 1
					if a1[x1] > a2[x2]:
						pv = 2
					ch += 1
					if pv == 1:
						x1 += 1
					else:
						x2 += 1
					while x1 < l1 or x2 < l2:
						if pv == 1:
							if x2 >= l2:
								break
							if a2[x2] > a1[x1 - 1]:
								ch += 1
								pv = 2
							x2 += 1
						else:
							if x1 >= l1:
								break
							if a2[x2 - 1] < a1[x1]:
								ch += 1
								pv = 1
							x1 += 1
					ch -= ch & 1
					ans = min(ans, n - ch)
		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')
if pypy:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
if profile:
	import cProfile
	cProfile.run('main()')
else:
	main()


t = int(input())
for _ in range(t):
	some = [[0 for i in range(10)] for i in range(10)]
	s = str(input())
	for i in s:
		a = int(i)
		for j in range(10):
			some[a][j] = some[j][a] + 1
	print(len(s) - max(max([max(i) for i in some]) // 2 * 2, max([some[i][i] for i in range(10)])))


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	d = defaultdict(int)
	st = set()
	for i in s:
		st.add(i)
	if len(st) == 1:
		print(0)
		continue
	digit = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09']
	for i in range(10, 100):
		digit.append(str(i))
	mx = 0
	for i in digit:
		ct = 0
		sec = False
		for j in s:
			if sec == False and j == i[0]:
				ct += 1
				sec = True
				continue
			if sec == True and j == i[1]:
				sec = False
				ct += 1
		if ct % 2 == 1 and i[0] != i[1]:
			ct -= 1
		mx = max(ct, mx)
	print(len(s) - mx)


from os import path
import sys, time
mod = int(1000000000.0 + 7)
from math import ceil, floor, gcd, log, log2, factorial, sqrt
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, permutations
from bisect import *
from functools import reduce
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
localsys = 0
start_time = time.time()
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)

def ceill(n, x):
	return (n + x - 1) // x
T = 1

def solve():
	a = list(map(int, S()))
	(n, cnt) = (len(a), [0] * 10)
	for i in a:
		cnt[i] += 1
	ans = n - max(cnt)
	b = [i for i in range(10) if cnt[i] > 0]
	for i in b:
		for j in b:
			if i == j:
				continue
			idx = 0
			l = 0
			while idx < n:
				while idx < n:
					if a[idx] == i:
						break
					idx += 1
				idx += 1
				while idx < n:
					if a[idx] == j:
						l += 1
						break
					idx += 1
				idx += 1
			ans = min(ans, n - 2 * l)
	print(ans)

def run():
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
run()
T = I() if T else 1
for _ in range(T):
	solve()
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()

def cnt(chars, s):
	p = 0
	cnt = 0
	for ch in s:
		if ch == chars[p]:
			p ^= 1
			cnt += 1
	return cnt - (cnt & 1)
for _ in range(t):
	s = g()
	n = len(s)
	b = Counter(s)
	ans = 0
	for ch in b:
		ans = max(ans, b[ch])
	for i in range(10):
		for j in range(i + 1, 10):
			ans = max(ans, cnt([str(i), str(j)], s), cnt([str(j), str(i)], s))
	print(n - ans)


t = int(input())
for _ in range(t):
	s = list(input())
	res = len(s) - 2
	for i in range(10):
		for j in range(10):
			(cur, ci, cj) = (0, 0, 0)
			(ii, jj) = (str(i), str(j))
			for c in s:
				if ci == cj and c == ii:
					ci += 1
				elif ci > cj and c == jj:
					cj += 1
				else:
					cur += 1
			res = min(cur + (1 if ci > cj and i != j else 0), res)
	print(res)


def main():
	t = int(input())
	for i in range(t):
		s = input()
		answer = 10 ** 9
		for i in range(9):
			for j in range(i + 1, 10):
				a = str(i)
				b = str(j)
				last = 'a'
				count = 0
				for f in s:
					if (f == a or f == b) and f != last:
						last = f
					else:
						count += 1
				if (len(s) - count) % 2 == 1:
					count += 1
				answer = min(answer, count)
		counts = [0 for i in range(10)]
		for f in s:
			counts[int(f)] += 1
		for i in counts:
			answer = min(answer, len(s) - i)
		print(answer)
main()


import math

def find_length(first, second):
	to_find = 0
	ops = [first, second]
	length = 0
	for char in arr:
		if char == ops[to_find]:
			length += 1
			to_find = 1 - to_find
	if to_find == 0:
		return length
	return length - 1
num_cases = int(input())
for _ in range(num_cases):
	arr = list(map(int, input().strip()))
	n = len(arr)
	count = [0 for _ in range(10)]
	for i in arr:
		count[i] += 1
	max_odd = max(count)
	max_even = 0
	for first in range(0, 10):
		for second in range(0, 10):
			if first == second:
				continue
			even = find_length(first, second)
			max_even = max(max_even, even)
	print(n - max(max_even, max_odd))


def find(first, second, s):
	total = 0
	last = -1
	for i in range(len(s)):
		if s[i] == first:
			if last == -1:
				last = first
				total += 1
			elif last == second:
				total += 1
				last = first
		elif s[i] == second:
			if last == first:
				last = second
				total += 1
	if total % 2 != 0:
		total -= 1
	return total

def solve(s, ans):
	max_len = 0
	for i in range(10):
		x = s.count(i)
		max_len = max(max_len, x)
	for i in range(10):
		for j in range(10):
			if i != j:
				max_len = max(max_len, find(i, j, s))
	ans.append(str(len(s) - max_len))

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


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

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

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	string = input()
	length = len(string)
	minCharacterremoved = float('inf')
	for i in [str(k) for k in range(10)]:
		for j in [str(k) for k in range(10)]:
			currComparitor = i
			charactersToRemove = 0
			for character in string:
				if character == currComparitor:
					currComparitor = [i, j][currComparitor == i]
				else:
					charactersToRemove += 1
			if (length - charactersToRemove) % 2 and i != j:
				charactersToRemove += 1
			minCharacterremoved = min(minCharacterremoved, charactersToRemove)
	print(minCharacterremoved)


from collections import Counter
t = int(input())
for _ in range(t):
	s = input()
	auxmatriz = Counter(s).most_common()
	x = auxmatriz[0][1]
	y = auxmatriz[0][1]
	matriz = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
	for i in range(9):
		matriz.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
	for i in s:
		num = int(i)
		for z in range(10):
			if num > z:
				if matriz[z][num] == 1 or (matriz[z][num] == 0 and matriz[num][z] == 0):
					matriz[z][num] = 0
					matriz[num][z] += 1
					if matriz[num][z] > y:
						y = matriz[num][z]
			elif num < z:
				if matriz[num][z] == 0:
					matriz[num][z] = 1
					matriz[z][num] += 1
					if matriz[z][num] > y:
						y = matriz[z][num]
	if y % 2 == 1:
		y -= 1
	if x > y:
		print(len(s) - x)
	else:
		print(len(s) - y)


from collections import Counter
t = int(input())
for _ in range(t):
	s = input()
	best = len(s) - max(Counter(s).values())
	longest = [[0 for _ in range(10)] for _ in range(10)]
	for c in s:
		ci = int(c)
		for j in range(10):
			if longest[ci][j] % 2 == 0:
				longest[ci][j] += 1
			if longest[j][ci] % 2:
				longest[j][ci] += 1
	best = min(best, len(s) - max((longest[i][j] - longest[i][j] % 2 for i in range(10) for j in range(10) if i != j)))
	print(best)


for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = n - 2
	g = {i: [] for i in '0123456789'}
	for i in range(n):
		g[s[i]].append(i)
	for a in '0123456789':
		for b in '0123456789':
			cs = 0
			i = j = 0
			aa = g[a]
			bb = g[b]
			ans = min(ans, n - len(aa))
			while i < len(aa):
				while j < len(bb) and aa[i] >= bb[j]:
					j += 1
				if j < len(bb):
					while i < len(aa) and aa[i] <= bb[j]:
						i += 1
				else:
					break
				cs += 1
			ans = min(ans, n - cs * 2)
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	a = list(map(int, list(input())))
	n = len(a)
	cnt = 0
	dic = {}
	ans = n - 2
	for x in a:
		if x not in dic.keys():
			dic[x] = 1
		else:
			dic[x] += 1
	for x in range(0, 10):
		for y in range(0, 10):
			if x == y:
				continue
			cnt = 0
			xx = 0
			while xx < n:
				while xx < n and a[xx] != x:
					xx += 1
				while xx < n and a[xx] != y:
					xx += 1
				if xx >= n:
					break
				cnt = cnt + 2
				ans = min(ans, n - cnt)
	print(min(ans, n - max(dic.values())))


import sys
import math
from decimal import *

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

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

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))

def solve():
	tt = I()
	for ii in range(tt):
		s = input()
		ss = [int(x) for x in s]
		n = len(ss)
		ans = n - 2
		count = [0] * 10
		for i in range(n):
			count[ss[i]] += 1
		for i in range(0, 10):
			ans = min(ans, n - count[i])
		for f in range(0, 10):
			for k in range(0, 10):
				res = 0
				for i in range(n):
					if res % 2 == 0 and f == ss[i]:
						res += 1
					elif res % 2 == 1 and k == ss[i]:
						res += 1
				if res % 2 == 1:
					continue
				ans = min(ans, n - res)
		print(ans)
		pass
solve()


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
	return int(stdin.readline().strip())

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

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

def solve():
	st = input()
	n = len(st)
	temp = Counter(st).most_common()[0][1]
	ans = max(temp, 2)
	find = []
	for i in range(10):
		for j in range(10):
			find.append(str(i) + str(j))
	for search in find:
		freq = 0
		i = 0
		for val in st:
			if val == search[i]:
				i ^= 1
				if i == 0:
					freq += 2
		ans = max(ans, freq)
	print(n - ans)

def main():
	solve()
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


from sys import stdin
for _ in range(int(stdin.readline())):
	t = stdin.readline().strip()
	ans = 0
	for i in range(10):
		cand1 = str(i)
		for j in range(10):
			cand2 = str(j)
			pos = 0
			flag = False
			for k in t:
				if k == cand1 and flag == False:
					flag = True
				elif k == cand2 and flag == True:
					pos += 2
					flag = False
			if flag and i == j:
				pos += 1
			ans = max(ans, pos)
	print(len(t) - ans)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

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
import sys

def solve(x):
	(a, b) = x
	count = 0
	for i in range(n):
		if count % 2 == 0:
			if s[i] == a:
				count += 1
		elif s[i] == b:
			count += 1
	if count % 2 == 0:
		return count
	else:
		return count - 1
t = int(input())
for _ in range(t):
	s = list(input())
	n = len(s)
	ans = inf
	for i in range(10):
		for j in range(10):
			k = str(i) + str(j)
			z1 = int(k)
			if i == j:
				z = s.count(str(i))
			else:
				z = solve(k)
			ans = min(n - z, ans)
	print(ans)


import sys
import math
from collections import Counter
from collections import deque
mod = 10 ** 9 + 7
inf = float('inf')

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

def LI():
	return list(map(int, sys.stdin.readline().split()))
t = I()
for _ in range(t):
	s = input()
	n = len(s)
	ans = n
	for i in range(10):
		for j in range(10):
			if i == j:
				ans = min(ans, n - s.count(str(i)))
				continue
			x = str(i)
			cnt = 0
			for k in range(n):
				if s[k] == x and s[k] == str(i):
					cnt += 1
					x = str(j)
				elif s[k] == x and s[k] == str(j):
					cnt += 1
					x = str(i)
			if cnt % 2:
				ans = min(ans, n - (cnt - 1))
			else:
				ans = min(ans, n - cnt)
	print(ans)


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	s = input().strip()
	R = 0
	for i in range(10):
		for j in range(10):
			tmp = 0
			x = [i, j]
			r = 0
			for c in s:
				c = int(c)
				if x[tmp] == c:
					tmp = 1 - tmp
					r += 1
			if i != j:
				r = r // 2 * 2
			R = max(R, r)
	print(len(s) - R)


for s in range(int(input())):
	string = input()
	store = [0 for i in range(10)]
	add = 0
	for i in string:
		add += 1
		store[int(i)] += 1
	store.sort()
	(maxi, plus, flag) = (9999999999, add, 1)
	a = store[-1]
	for i in range(10):
		for j in range(10):
			(add, flag) = (0, 1)
			for k in range(plus):
				if int(string[k]) == i and flag == 1:
					add += 1
					flag = 0
				elif int(string[k]) == j and flag == 0:
					add += 1
					flag = 1
			if add % 2 == 1:
				add -= 1
			maxi = min(maxi, plus - add)
	maxi = min(maxi, plus - a)
	print(maxi)


nos = '0123456789'
son = '9876543210'
for _ in range(int(input())):
	s = input().strip()
	pairs = []
	d = {i: 0 for i in nos}
	for j in s:
		d[j] += 1
	ans = max(d.values())
	for i in range(len(nos)):
		for j in range(i + 1, len(nos)):
			pairs.append([nos[i], nos[j]])
	for i in range(len(son)):
		for j in range(i + 1, len(son)):
			pairs.append([son[i], son[j]])
	for i in pairs:
		(last, cur) = (0, 0)
		for j in s:
			if j == i[last]:
				cur += 1
				last = 1 - last
		if last == 1:
			cur -= 1
		ans = max(ans, cur)
	print(len(s) - ans)


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

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

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

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 myceil(x, y):
	return (x + y - 1) // y

def Solution(s):
	ans = 0
	for i in range(10):
		for j in range(10):
			c1 = str(i)
			c2 = str(j)
			tmp = 0
			for c in s:
				if c == c1 and tmp % 2 == 0:
					tmp += 1
				elif c == c2 and tmp % 2 == 1:
					tmp += 1
			if c1 != c2:
				if tmp % 2:
					tmp -= 1
			ans = max(ans, tmp)
	print(len(s) - ans)

def main():
	for _ in range(get_int()):
		Solution(get_string())
main()


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	ans = [0] * 10
	for i in range(n):
		ans[ord(s[i]) - ord('0')] = ans[ord(s[i]) - ord('0')] + 1
	ans.sort()
	mx = ans[9]
	for i in range(10):
		for j in range(10):
			c = 0
			if j == i:
				continue
			b = 0
			for k in range(n):
				if b == 0 and ord(s[k]) - ord('0') == i:
					b = 1
					c = c + 1
				elif b == 1 and ord(s[k]) - ord('0') == j:
					b = 0
					c = c + 1
				mx = max(c - c % 2, mx)
	print(n - max(mx, ans[9]))


t = int(input())
for _ in range(t):
	s = input()
	l = [[0 for i in range(10)] for i in range(10)]
	d = {}
	d = [0 for i in range(10)]
	boolar = [[False for i in range(10)] for i in range(10)]
	for i in s:
		d[int(i)] += 1
		x = int(i)
		for j in range(10):
			if boolar[j][x]:
				l[j][x] += 1
				boolar[j][x] = False
			if x != j:
				boolar[x][j] = True
	m = 0
	for i in range(10):
		for j in range(10):
			m = max(m, l[i][j])
	a = len(s) - 2 * m
	b = len(s) - max(d)
	if max(d) == len(s):
		print(0)
	else:
		print(min(a, b))


for _ in range(int(input())):
	num = input()
	maxLen = 2
	cnt = [0 for i in range(10)]
	for d in num:
		cnt[int(d)] += 1
		maxLen = max(maxLen, cnt[int(d)])
	for a in range(10):
		for b in range(10):
			(pre, cur) = (-1, 0)
			for d in num:
				x = int(d)
				if x != pre and (x == a or x == b):
					pre = x
					cur += 1
			maxLen = max(maxLen, cur - cur % 2)
	print(len(num) - maxLen)


from collections import defaultdict, Counter
from math import log, ceil, floor

def solve():
	s = list(input())
	d = [0 for i in range(11)]
	for i in s:
		d[int(i)] += 1
	ans1 = max(d)
	ans2 = 0
	for i in range(10):
		for j in range(10):
			if i != j:
				x = 1
				c = 0
				for k in s:
					if int(k) == i and x:
						c += 1
						x = 0
					elif int(k) == j and (not x):
						c += 1
						x = 1
				ans2 = max(ans2, c)
	if ans2 & 1:
		ans2 -= 1
	print(len(s) - max(ans2, ans1))
t = 1
t = int(input())
for _ in range(t):
	solve()


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
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(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 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 p in range(I()):
	v = [[0 for i in range(10)] for i in range(10)]
	val = [[0 for i in range(10)] for i in range(10)]
	ln = 0
	for i in S():
		i = int(i)
		for j in range(10):
			if i == j:
				val[j][i] += 1
			elif v[j][i]:
				val[j][i] += 2
				v[j][i] = 0
			if not v[i][j]:
				v[i][j] = 1
		ln += 1
	print(ln - max([max(i) for i in val]))


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	arr = list(s)
	n = len(s)
	d = defaultdict(int)
	for i in arr:
		d[i] += 1
	ans = 0
	for i in d:
		ans = max(d[i], ans)
	t = '0123456789'
	dp = [[] for i in range(10)]
	for i in range(len(s)):
		dp[int(s[i])].append(i)
	t = list(t)
	for i in range(len(t)):
		for j in range(len(t)):
			if i == j:
				continue
			x = t[i]
			y = t[j]
			tu = 0
			cnt = 0
			for k in range(n):
				if tu % 2 == 0:
					if s[k] == x:
						cnt += 1
						tu += 1
				elif s[k] == y:
					cnt += 1
					tu += 1
			if cnt % 2 != 0:
				cnt -= 1
			ans = max(ans, cnt)
	print(n - ans)


for _ in range(int(input())):
	s = input()
	m = 0
	for i in range(10):
		for j in range(10):
			c = i
			t = 0
			for k in s:
				if k == str(c):
					t += 1
					if c == j:
						c = i
					else:
						c = j
			if t % 2 and i != j:
				t -= 1
			m = max(m, t)
	print(len(s) - m)


from sys import stdin, stdout
k = ''

def yark(a, i, j):
	z = 0
	p = str(i)
	f = p
	for k in a:
		if k == f:
			z += 1
			f = p if f != p else str(j)
	if i != j and z & 1:
		z -= 1
	return z
for t in range(int(stdin.readline())):
	a = stdin.readline()
	ans = 0
	for i in range(10):
		for j in range(10):
			ans = max(ans, yark(a, i, j))
	k += str(len(a) - ans - 1) + ' '
stdout.write(k)


import sys
import math, bisect
from collections import defaultdict
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, OrderedDict

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

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	s = input()
	maxi = -10 ** 18
	for i in range(10):
		for j in range(10):
			if i == j:
				maxa = -10 ** 18
				c2 = 0
				for z1 in range(len(s)):
					if ord(s[z1]) - 48 == i:
						c2 += 1
				maxa = max(c2, maxa)
			else:
				z = 0
				c1 = 0
				h = len(s)
				while z < h - 1:
					if ord(s[z]) - 48 == i:
						z += 1
						while z != h and ord(s[z]) - 48 != j:
							z += 1
						if z != h:
							c1 += 1
							z += 1
					else:
						z += 1
				maxi = max(maxi, 2 * c1)
			maxi = max(maxa, maxi)
	print(len(s) - maxi)


t = int(input())
for _ in range(t):
	s = input()
	d = {}
	for i in range(len(s)):
		d[s[i]] = 0
	for i in range(len(s)):
		d[s[i]] += 1
	mini = 1000000000.0
	maxi = 0
	for key in d:
		maxi = max(maxi, d[key])
	o = len(s)
	mini = min(mini, o - maxi)
	for i in range(10):
		for j in range(10):
			if i != j:
				p = []
				for k in s:
					if int(k) == i or int(k) == j:
						p.append(k)
				l = str(''.join(p))
				z = 2 * max(l.count(str(i) + str(j)), l.count(str(j) + str(i)))
				mini = min(mini, o - z)
	print(mini)


import math

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

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

def bs(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return arr[mid]
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def swap(list, pos1, pos2):
	(list[pos1], list[pos2]) = (list[pos2], list[pos1])
	return list

def subarrayBitwiseOR(A):
	res = set()
	pre = {0}
	for x in A:
		pre = {x | y for y in pre} | {x}
		res |= pre
	return len(res)
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	maxx = 0
	maxxs = 0
	for i in range(0, 10):
		maxxs = max(maxxs, s.count(str(i)))
	for i in range(0, 100):
		cnt = 0
		y = str(i)
		if len(y) == 1:
			y = '0' + y
		f = 0
		for j in range(n):
			if s[j] == y[0]:
				f = 1
			elif s[j] == y[1] and f == 1:
				cnt += 1
				f = 0
		maxx = max(maxx, cnt)
	print(min(len(s) - 2 * maxx, len(s) - maxxs))


for _ in range(int(input())):
	s = input()
	m = 0
	for i in range(10):
		m = max(m, s.count(str(i)))
	ans1 = len(s) - m
	second = 0
	for i in range(10):
		for j in range(i + 1, 10):
			last = ''
			c = 0
			for k in s:
				if k == str(i) or k == str(j):
					if k != last:
						c += 1
						last = k
			if c % 2 == 0:
				second = max(second, c)
			else:
				second = max(second, c - 1)
	ans2 = len(s) - second
	ans3 = len(s) - 2
	print(min(ans1, ans2, ans3))


import bisect
for _ in range(int(input())):
	st = input()
	dic = {}
	le = len(st)
	for i in range(le):
		if st[i] in dic:
			dic[st[i]].append(i)
		else:
			dic[st[i]] = [i]
	dicle = {}
	for i in dic:
		dicle[i] = len(dic[i])
	ans = 0
	for i in dic:
		for j in dic:
			if i != j:
				ind = dic[i][0]
				ii = 0
				while True:
					if ii % 2 == 0:
						xx = bisect.bisect(dic[j], ind)
						if xx == dicle[j]:
							break
						else:
							ind = dic[j][xx]
					else:
						xx = bisect.bisect(dic[i], ind)
						if xx == dicle[i]:
							break
						else:
							ind = dic[i][xx]
					ii += 1
				ans = max(ans, (ii + 1) // 2)
	ans = 2 * ans
	for i in dicle:
		ans = max(ans, dicle[i])
	print(le - ans)


t = int(input())
for i in range(t):
	s = input()
	n = len(s)
	ans = 2
	for j in range(10):
		for k in range(10):
			l = [str(j), str(k)]
			c = 0
			a = 0
			for p in s:
				if p == l[a]:
					c += 1
					a ^= 1
			if c % 2 and l[0] != l[1]:
				ans = max(ans, c - 1)
			else:
				ans = max(ans, c)
	print(n - ans)


for i in range(int(input())):
	s = input()
	c = 0
	for j in range(10):
		for k in range(10):
			a = 0
			go = True
			bo = False
			for m in s:
				x = int(m)
				if x == j and go:
					a += 1
					go = False
					bo = True
				elif x == k and bo:
					a += 1
					go = True
					bo = False
			if j != k:
				a -= a & 1
			c = max(c, a)
	print(len(s) - c)


import sys
input = sys.stdin.readline
aaaa = list()
for kek in range(int(input())):
	s = input().split()[0]
	ans = 0
	for i in range(10):
		for j in range(10):
			flg = True
			answer = 0
			for x in s:
				if flg and int(x) == i:
					answer += 1
					flg = False
				elif flg == False and int(x) == j:
					answer += 1
					flg = True
			if i == j:
				ans = max(answer, ans)
			else:
				ans = max(answer // 2 * 2, ans)
	aaaa.append(len(s) - ans)
print(*aaaa, sep='\n')


import sys
input = sys.stdin.readline

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

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

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

def invr():
	return map(int, input().split())
T = inp()
for t in range(T):
	S = insr()
	if len(S) < 3:
		print(0)
	else:
		maxx = 0
		for i in range(100):
			curr = str(i)
			if i < 10:
				curr = '0' + curr
			fl = True
			tmp = 0
			for j in range(len(S)):
				if fl:
					if S[j] == curr[0]:
						fl = False
				elif S[j] == curr[1]:
					fl = True
					tmp += 2
			maxx = max(tmp, maxx)
		for i in range(10):
			tmp = S.count(str(i))
			maxx = max(tmp, maxx)
		print(len(S) - maxx)


def det(s, i, j):
	ans = 0
	curr = i
	for a in s:
		if a == curr:
			ans += 1
			if curr == i:
				curr = j
			else:
				curr = i
	if i == j:
		return ans
	return ans // 2 * 2
for t in range(int(input())):
	s = list(map(int, list(input())))
	ans = 0
	for i in range(10):
		for j in range(10):
			ans = max(ans, det(s, i, j))
	print(len(s) - ans)


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		strN = input()
		flag = False
		temp = strN[0]
		for i in strN:
			if i != temp:
				flag = True
		if not flag or len(strN) == 2:
			print(0)
			continue
		ans = len(strN)
		for i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
			for j in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
				if j == i:
					continue
				cnt = 0
				tempFlag = False
				for k in strN:
					if k == i and (not tempFlag):
						tempFlag = True
					elif k == j and tempFlag:
						cnt += 2
						tempFlag = False
				ans = min(ans, len(strN) - cnt)
		for i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
			cnt = 0
			for k in strN:
				if k == i:
					cnt += 1
			ans = min(ans, len(strN) - cnt)
		print(ans)
	return
main()


def good(s):
	maxx = 0
	for i in range(10):
		for j in range(10):
			if i != j:
				first = False
				pair = 0
				for dig in s:
					if not first and str(i) == dig:
						first = True
					elif first and str(j) == dig:
						pair += 1
						first = False
				maxx = max(maxx, pair)
	l = [0 for i in range(10)]
	for i in s:
		l[int(i)] += 1
	ans = max(2 * maxx, max(l))
	return len(s) - ans
t = int(input())
for t in range(t):
	s = input()
	print(good(s))


from sys import stdin, stdout
import math
cin = stdin.readline
cout = stdout.write
mp = lambda : list(map(int, cin().split()))

def chars():
	s = cin()
	return list(s[:len(s) - 1])

def pl(a):
	for val in a:
		cout(str(val) + ' ')
	cout('\n')
from collections import Counter
(t,) = mp()
for _ in range(t):
	d = cin()[:-1]
	ln = len(d)
	s = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	ans = 0
	for ch in s:
		x = d.find(ch)
		if x < 0:
			continue
		for ch2 in s:
			f = temp = 0
			if ch == ch2:
				temp = 1
			for i in range(x + 1, ln):
				if ch == ch2:
					if d[i] == ch:
						temp += 1
				elif d[i] == ch2 and (not f):
					f = 1
					temp += 1
				elif d[i] == ch and f:
					f = 0
			if ch != ch2:
				temp *= 2
			ans = max(temp, ans)
	cout(str(ln - max(ans, 2)) + '\n')


import sys
import math
read = sys.stdin.buffer.read
readlines = sys.stdin.buffer.readlines
t = int(input())
for case in range(t):
	s = input()
	ans = 0
	for i in range(10):
		for j in range(10):
			i_bit = 0
			ij_len = 0
			i_len = 0
			for k in s:
				if i_bit == 0:
					if i == int(k):
						i_bit = 1
						ij_len += 1
				elif j == int(k):
					i_bit = 0
					ij_len += 1
				if i == int(k):
					i_len += 1
			ans = max(ans, i_len, ij_len // 2 * 2)
	print(min(len(s) - 2, len(s) - ans))