#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    string s;
    cin >> s;
    int ans = 1;
    for (int i = 0; i <= 9; i++) {
      for (int j = 0; j <= 9; j++) {
        bool f = 0;
        int sum = 0;
        for (int k = 0; k < s.size(); k++) {
          if (s[k] - '0' == i || s[k] - '0' == j) {
            if (f == 0) {
              if (s[k] - '0' == i) {
                f = 1;
                sum++;
              }
            } else {
              if (s[k] - '0' == j) {
                f = 0;
                sum++;
              }
            }
          }
        }
        if (i != j && sum % 2) sum--;
        ans = max(ans, sum);
      }
    }
    cout << s.size() - ans << endl;
  }
  return 0;
}
