#include <bits/stdc++.h>
using namespace std;
bool cmp(pair<int, int> a, pair<int, int> b) {
  return (a.first < b.first) || (a.first == b.first && a.second > b.second);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    int b[10] = {0};
    char c;
    int m = 0;
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        {
          char c = i + '0';
          char d = j + '0';
          int var = 1;
          int cnt = 0;
          for (int i = 0; i < s.length(); i++) {
            if (s[i] == c && var)
              cnt++, var = 0;
            else if (s[i] == d && !var)
              cnt++, var = 1;
          }
          if (cnt % 2 && i != j) cnt--;
          m = max(m, cnt);
        }
      }
    }
    cout << s.length() - m << endl;
  }
}
