#include <bits/stdc++.h>
using namespace std;
void solve() {
  string s;
  cin >> s;
  long long int n = s.size();
  vector<long long int> v(100);
  long long int ans = n - 1;
  for (long long int i = 0; i < n; i++) {
    v[s[i] - '0']++;
  }
  for (long long int i = 0; i <= 9; i++) {
    ans = min(ans, n - v[i]);
  }
  for (long long int x = 0; x <= 9; x++) {
    for (long long int y = 0; y <= 9; y++) {
      if (x == y) continue;
      long long int d = 0, mark = 0;
      for (long long int i = 0; i < n; i++) {
        if (mark == 0 && s[i] - '0' == x) {
          d++;
          mark ^= 1;
        } else if (mark == 1 && s[i] - '0' == y) {
          d++;
          mark ^= 1;
        }
      }
      d = 2 * (d / 2);
      ans = min(ans, n - d);
    }
  }
  cout << ans << endl;
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int q = 1;
  cin >> q;
  while (q--) {
    solve();
  }
  return 0;
}
