#include <bits/stdc++.h>
using namespace std;
int main() {
  int test;
  cin >> test;
  while (test--) {
    string s;
    cin >> s;
    int ans = INT_MAX;
    unordered_map<char, int> mp;
    int n = s.size();
    for (int i = 0; i < s.size(); i++) {
      mp[s[i]]++;
    }
    for (auto x : mp) {
      ans = min(ans, n - x.second);
    }
    for (int i = 0; i <= 9; i++) {
      for (int j = 0; j <= 9; j++) {
        int val = i;
        int ans1 = 0;
        for (int k = 0; k < s.size(); k++) {
          int value = s[k] - '0';
          if (value == val) {
            if (val == i) {
              val = j;
              ans1++;
            } else if (val == j && j != i) {
              val = i;
              ans1++;
            }
          }
        }
        ans1 = (ans1 / 2) * 2;
        ans = min(ans, n - ans1);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
