#include <bits/stdc++.h>
using namespace std;
int mod = 1e9 + 7;
int op = 1e8;
int main() {
  int t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    int res = 2;
    int n = s.length();
    int ans;
    for (int i = 0; i < 10; i++) {
      ans = 0;
      for (int j = 0; j < n; j++) {
        if (s[j] - '0' == i) ans++;
      }
      res = max(res, ans);
    }
    int state;
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        if (j == i) continue;
        ans = 0;
        state = 0;
        for (int k = 0; k < n; k++) {
          if (s[k] - '0' == i && state == 0) {
            state = 1;
          }
          if (s[k] - '0' == j && state == 1) {
            state = 0;
            ans = ans + 2;
          }
        }
        res = max(res, ans);
      }
    }
    cout << n - res << endl;
  }
}
