import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable char [] digits = "0123456789";

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		int res = 0;
		foreach (char c; digits)
		{
			res = max (res, s.count (c).to !(int));
		}
		foreach (char c; digits)
		{
			foreach (char d; digits)
			{
				int pos = 0;
				int cur = 0;
				while (true)
				{
					while (pos < s.length && s[pos] != c)
					{
						pos += 1;
					}
					pos += 1;
					while (pos < s.length && s[pos] != d)
					{
						pos += 1;
					}
					if (pos >= s.length)
					{
						break;
					}
					pos += 1;
					cur += 2;
				}
				res = max (res, cur);
			}
		}
		writeln (s.length - res);
	}
}
