#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 n = s.length();
    string cm_s = "0123456789";
    int ans = INT_MAX;
    for (int i = 0; i < 10; i++) {
      int cnt = 0;
      for (int j = 0; j < n; j++) {
        if (s[j] == cm_s[i]) {
          cnt++;
        }
      }
      ans = min(ans, n - cnt);
    }
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        bool first = false;
        int cnt1 = 0;
        for (int k = 0; k < n; k++) {
          if (first == false) {
            if (s[k] == cm_s[i]) {
              cnt1++;
              first = true;
            }
          } else {
            if (s[k] == cm_s[j]) {
              cnt1++;
              first = false;
            }
          }
        }
        if (cnt1 % 2) cnt1--;
        ans = min(ans, n - cnt1);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
