#include <bits/stdc++.h>
using namespace std;
const int64_t Nmax = 1e9 + 7;
const int64_t mod = 1000000007;
vector<int64_t> prime;
int64_t is_power_of_two(int64_t a) { return a && (!(a & (a - 1))); }
int64_t isperfectsquare(int64_t a) {
  double b = sqrt(a);
  return (b - ceil(b) == 0);
}
int64_t pow(int64_t a, int64_t b, int64_t m) {
  a = a % m;
  int64_t res = 1;
  while (b > 0) {
    if (b & 1) {
      res = res * a % m;
    }
    a = a * a % m;
    b = b / 2;
  }
  return res;
}
void seive(int64_t n) {
  bool isprime[n];
  memset(isprime, true, sizeof(isprime));
  prime.push_back(2);
  for (int64_t i = 3; i <= sqrt(n); i += 2) {
    if (isprime[i]) {
      for (int64_t j = i * i; j <= n; j += i) {
        isprime[j] = false;
      }
    }
  }
  for (int64_t i = 3; i <= n; i += 2) {
    if (isprime[i]) {
      prime.push_back(i);
    }
  }
}
void solve() {
  string s;
  cin >> s;
  int64_t f[10] = {0};
  int64_t mx = -1, mxx = -1;
  for (auto e : s) {
    f[e - '0']++;
  }
  for (auto e : f) {
    mx = max(mx, e);
  }
  mx = s.length() - mx;
  for (int64_t i = 0; i <= 9; i++) {
    for (int64_t j = 0; j <= 9; j++) {
      int64_t chg = 1;
      int64_t rr = 0;
      for (int64_t k = 0; k <= s.length() - 1; k++) {
        if (chg) {
          if ((s[k] - '0') == i) {
            chg = 0;
            rr++;
          }
        } else {
          if ((s[k] - '0') == j) {
            chg = 1;
            rr++;
          }
        }
      }
      if (rr & 1) {
        rr--;
      }
      mx = min(mx, (int64_t)(s.length() - rr));
    }
  }
  cout << mx << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int64_t t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
