#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  for (int t = 0; t < T; ++t) {
    string s;
    cin >> s;
    int n = s.size();
    vector<int> v;
    for (int i = 0; i < n; i++) {
      v.push_back(s[i] - '0');
    }
    int minlen = INT_MAX;
    for (int t1 = 0; t1 <= 9; t1++) {
      for (int t2 = 0; t2 <= 9; t2++) {
        int count = 0, flag = 0;
        for (int i = 0; i < n; i++) {
          if (flag == 0 && v[i] == t1) {
            flag = 1;
            count++;
          } else {
            if (flag == 1 && v[i] == t2) {
              flag = 0;
              count++;
            }
          }
        }
        int ans = 0;
        if (t1 == t2) {
          ans = n - count;
        } else {
          ans = n - count + flag;
        }
        minlen = min(ans, minlen);
      }
    }
    cout << minlen << "\n";
  }
}
