#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  while (T--) {
    string S;
    cin >> S;
    int i = 0, n = S.size();
    int A[10] = {0}, C[10] = {0}, sum = 0, sum1 = 0;
    vector<bool> B(10);
    while (S[i] != '\0') {
      A[S[i] - '0']++;
      i++;
    }
    for (int i = 0; i < 10; i++) {
      sum = max(sum, A[i]);
    }
    for (int i = 0; i < 10; i++) {
      sum1 = 0;
      for (int j = 0; j < n;) {
        for (int k = 0; k < 10; k++) B[k] = 0;
        if (S[j] - '0' == i) {
          j++;
          while (S[j] - '0' != i && j < n) {
            if (!B[S[j] - '0']) {
              C[S[j] - '0'] += 2;
              B[S[j] - '0'] = 1;
            }
            j++;
          }
        } else
          j++;
      }
      for (int j = 0; j < 10; j++) {
        sum = max(sum, C[j]);
        C[j] = 0;
      }
    }
    cout << n - sum << "\n";
  }
  return 0;
}
