#include <bits/stdc++.h>
using namespace std;
int has, arr[20], flag[20][20];
string s;
void f(int a, int b) {
  char p[2], q, now;
  int hit = 0;
  p[0] = char(a + '0'), p[1] = char(b + '0'), now = 0;
  for (int i = 0; i < s.size(); i++) {
    if (s[i] == p[now]) {
      if (now == 1) hit += 2;
      now = 1 - now;
    }
  }
  int l = s.size();
  has = min(has, l - hit);
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> s;
    has = 1000000009;
    for (int i = 0; i <= 9; i++) arr[i] = 0;
    for (int i = 0; i < s.size(); i++) arr[s[i] - '0']++;
    int k = 0;
    for (int i = 0; i <= 9; i++) k = max(k, arr[i]);
    for (int i = 0; i <= 9; i++) {
      for (int j = 0; j <= 9; j++) {
        if (i == j) continue;
        f(i, j);
        f(j, i);
      }
    }
    int n = s.size();
    has = min(has, min(n - 2, n - k));
    cout << has << endl;
  }
}
