#include <bits/stdc++.h>
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }
using namespace std;
int main() {
  int nq;
  cin >> nq;
  while (nq--) {
    string str;
    cin >> str;
    auto arr = vector<int>(str.size());
    for (int i = 0; i < arr.size(); i++) arr[i] = str[i] - '0';
    int ans = arr.size() - 2;
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        int found = 0;
        for (int k = 0; k < arr.size(); k++) {
          if (arr[k] == (found % 2 ? i : j)) found++;
        }
        if (found % 2 && i != j) found--;
        int cur = arr.size() - found;
        ans = min(ans, cur);
      }
    }
    std::cout << ans << "\n";
  }
  return 0;
}
