#include <bits/stdc++.h>
using namespace std;
long long md(string& s, long long x, long long y) {
  long long rv = 0;
  bool oy = false;
  for (long long i = 0; i < (long long)s.size(); ++i) {
    if (oy) {
      if (s[i] == '0' + y) {
        oy = !oy;
      } else {
        rv++;
      }
    } else {
      if (s[i] == '0' + x) {
        oy = !oy;
      } else {
        rv++;
      }
    }
  }
  rv += oy;
  return rv;
}
long long C(string& s) {
  vector<long long> c(10, 0);
  for (auto si : s) {
    c[si - '0']++;
  }
  long long rv = s.size() - 2;
  for (long long i = 0; i <= 9; ++i) {
    rv = min(rv, ((long long)s.size()) - c[i]);
    for (long long j = 0; j < i; ++j) {
      rv = min(rv, md(s, i, j));
    }
    for (long long j = i + 1; j <= 9; ++j) {
      rv = min(rv, md(s, i, j));
    }
  }
  return rv;
}
int main(void) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t;
  cin >> t;
  for (; t-- > 0;) {
    string s;
    cin >> s;
    cout << C(s) << endl;
  }
  return 0;
}
