#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    long long n = s.size();
    long long m = 0, c = 0;
    for (long long i = 0; i < 10; i++) {
      for (long long j = 0; j < 10; j++) {
        for (long long k = 0; k < n; k++) {
          if (c % 2 == 0 && s[k] == ('0' + i))
            c++;
          else if (c % 2 == 1 && s[k] == ('0' + j))
            c++;
        }
        if (i != j && c % 2 == 1) c--;
        m = max(m, c);
        c = 0;
      }
    }
    cout << n - m << "\n";
  }
  return 0;
}
