#include <bits/stdc++.h>
using namespace std;
int fun(string s, int a, int b) {
  int i, j, k, n = s.length();
  int cnt = 0;
  i = 0;
  j = 0;
  int cnta = 0, cntb = 0;
  for (i = 0; i < n; i++) {
    if (s[i] - '0' == a && cnta == 0) {
      cnta = 1;
    } else if (s[i] - '0' == b && cnta == 1) {
      cnta = 0;
      cnt++;
    }
  }
  return n - cnt * 2;
}
int fun2(string s) {
  int arr[10] = {0}, i;
  for (i = 0; i < 10; i++) arr[i] = 0;
  for (i = 0; i < s.length(); i++) {
    arr[s[i] - '0']++;
  }
  return *max_element(arr, arr + 10);
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int i, j, k, n;
    string s;
    cin >> s;
    n = s.length();
    int mini = INT_MAX;
    i = 5, j = 1;
    for (i = 0; i < 10; i++) {
      for (j = 0; j < 10; j++) {
        string temp = s;
        int p = fun(temp, i, j);
        mini = min(mini, p);
      }
    }
    int a = fun2(s);
    cout << min(mini, n - a) << endl;
  }
}
