#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  int tt;
  cin >> tt;
  while (tt--) {
    string s;
    cin >> s;
    int n = s.length();
    if (n == 2) {
      cout << 0 << "\n";
    } else {
      char ch = '0';
      int a[10];
      int mx = 0;
      for (int i = 0; i < 10; i++) {
        a[i] = count(s.begin(), s.end(), ch);
        ch++;
        mx = max(mx, a[i]);
      }
      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
          if (i != j) {
            int cnt = 0;
            int x[2];
            x[0] = i, x[1] = j;
            int val = 0;
            for (int k = 0; k < n; k++) {
              int no = s[k] - '0';
              if (x[val] == no) {
                cnt++;
                val++;
                val %= 2;
              }
            }
            if (cnt & 1) cnt--;
            mx = max(mx, cnt);
          }
      cout << n - mx << "\n";
    }
  }
  return 0;
}
