#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ;
  long long int t;
  cin >> t;
  long long int w = t;
  while (t--) {
    string s;
    cin >> s;
    long long int n = s.size();
    vector<long long int> occ(10, 0);
    vector<vector<long long int> > a(10, vector<long long int>(10, 0));
    for (long long int i = 0; i < (n); i++) {
      occ[s[i] - '0']++;
    }
    for (long long int i = 0; i < (10); i++) {
      set<long long int> se;
      long long int f = 0;
      for (long long int j = 0; j < (n); j++) {
        if (s[j] == ('0' + i)) {
          f = 1;
          vector<long long int> v((se).begin(), (se).end());
          long long int r = v.size();
          for (long long int k = 0; k < (r); k++) a[i][v[k]]++;
          se.clear();
        } else
          se.insert((long long int)(s[j] - '0'));
      }
    }
    long long int maxi = 0;
    for (long long int i = 0; i < (10); i++) {
      for (long long int j = 0; j < (10); j++) maxi = max(maxi, a[i][j]);
    }
    long long int po = *max_element((occ).begin(), (occ).end());
    cout << min(n - 2 * maxi, n - po) << "\n";
  }
}
