#include <bits/stdc++.h>
using namespace std;
void yes() { cout << "YES" << endl; }
void no() { cout << "NO" << endl; }
int dx[] = {1, 0, -1, 0, -1, -1, 1, 1};
int dy[] = {0, 1, 0, -1, -1, 1, -1, 1};
const long long INF = 8e18 + 8;
const double EPS = 1e-9;
const long long MOD = 1e9 + 7;
void solve() {
  string s;
  cin >> s;
  int n = (int)((s).size());
  vector<int> cnt(10, 0);
  int res = 0;
  for (int i = 0; i < n; i++) {
    cnt[s[i] - '0']++;
    res = max(res, cnt[s[i] - '0']);
  }
  for (int i = 0; i <= 9; i++) {
    char c1 = char(i + '0');
    for (int j = 0; j <= 9; j++) {
      char c2 = char(j + '0');
      if (i == j) continue;
      int last = -1;
      int cnt = 0;
      for (int k = 0; k < n; k++) {
        if (s[k] != c1 and s[k] != c2) continue;
        if (last == -1) {
          last = s[k] - '0';
          cnt++;
        } else if (last == i and s[k] == c2) {
          last = j;
          cnt++;
        } else if (last == j and s[k] == c1) {
          last = i;
          cnt++;
        }
      }
      res = max(res, cnt - (cnt & 1));
    }
  }
  cout << n - res << endl;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  bool tests = 1;
  int t = 1;
  if (tests) cin >> t;
  for (int i = 1; i <= t; i++) {
    solve();
  }
  return 0;
}
