#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pr = pair<int, int>;
int mx = std::numeric_limits<int>::max();
int main() {
  int t = 1;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    set<char> s_set;
    int min_del = mx;
    for (auto c : s) s_set.insert(c);
    for (auto a : s_set) {
      for (auto b : s_set) {
        int toDel = 0;
        if (a == b) {
          for (auto cc : s)
            if (cc != a) toDel++;
        } else {
          char curc = 'n';
          char first_c = 'n';
          int count = 0;
          for (int i = 0; i < int(s.size()); ++i) {
            if (s[i] == a or s[i] == b) {
              if (curc == 'n') {
                curc = s[i];
                first_c = curc;
                count++;
              } else if (curc == s[i])
                toDel++;
              else {
                curc = s[i];
                count++;
              }
            } else {
              toDel++;
            }
          }
          if (first_c == curc and count > 1) toDel++;
        }
        min_del = min(toDel, min_del);
      }
    }
    cout << min_del << endl;
  }
  return 0;
}
