#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    map<char, long long> mp;
    for (char c : s) mp[c]++;
    long long ans = 1e18;
    for (char i = '0'; i <= '9'; i++) {
      for (char j = '0'; j <= '9'; j++) {
        long long l = 0;
        string str = "";
        for (int k = 0; k < s.size(); k++) {
          if (l & 1) {
            if (s[k] == i) l++, str += s[k];
          } else {
            if (s[k] == j) l++, str += s[k];
          }
        }
        if (str.size() && i != j)
          if (str[str.size() - 1] == str[0]) str.pop_back();
        ans = min(ans, (long long)(s.size() - str.size()));
      }
    }
    cout << ans << endl;
  }
  return 0;
}
