#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long int llINF = 0x3f3f3f3f3f3f3f;
int main() {
  int t;
  cin >> t;
  while (t--) {
    vector<int> pos[10];
    string s;
    cin >> s;
    int n = s.size();
    for (int i = 0; i < n; i++) {
      pos[s[i] - '0'].push_back(i);
    }
    int ans = -1;
    for (int i = 0; i < 10; i++) ans = max(ans, (int)pos[i].size());
    for (int i = 0; i < 10; i++) {
      if (pos[i].size() == 0) continue;
      for (int j = 0; j < 10; j++) {
        if (i == j) continue;
        if (pos[j].size() == 0) continue;
        int ni = pos[i].size(), nj = pos[j].size();
        int md = 0, curi = 0, curj = 0, last = -1;
        int plc = 0;
        while (curi < ni && curj < nj) {
          while (!md && curi < ni && pos[i][curi] < last) curi++;
          if (!md && curi < ni) {
            last = pos[i][curi];
            plc++;
            md ^= 1;
            continue;
          }
          while (md && curj < nj && pos[j][curj] < last) curj++;
          if (md && curj < nj) {
            last = pos[j][curj];
            md ^= 1;
            plc++;
            continue;
          }
        }
        ans = max(ans, (plc / 2) * 2);
      }
    }
    printf("%d\n", n - ans);
  }
}
