#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    int n = s.length();
    int mp[10];
    memset(mp, 0, sizeof(mp));
    for (int i = 0; i < n; i++) {
      mp[s[i] - 48]++;
    }
    int ans = 0;
    for (int i = 0; i < 10; i++) {
      ans = max(ans, mp[i]);
    }
    ans = n - ans;
    int cnt = 0;
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        cnt = 0;
        bool f = 0;
        for (auto c : s) {
          int d = c - '0';
          if (f == 0 && d == i) {
            cnt++;
            f = 1;
          } else if (f == 1 && d == j) {
            cnt++;
            f = 0;
          }
        }
        cnt = cnt / 2 * 2;
        ans = min(ans, n - cnt);
      }
    }
    cout << ans << endl;
  }
}
