#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    char s[200001];
    scanf("%s", s);
    int n = strlen(s);
    int ans = n - 2;
    for (int i = '0'; i <= '9'; i++) {
      for (int j = '0'; j <= '9'; j++) {
        vector<char> arr;
        for (int k = 0; k < n; k++) {
          if (s[k] != i && s[k] != j) continue;
          if (i == j) {
            arr.push_back(s[k]);
          } else {
            if (arr.size() == 0 || s[k] != arr[arr.size() - 1])
              arr.push_back(s[k]);
          }
        }
        if (arr.size() < 2) continue;
        int abc = n - arr.size();
        if (i == j) {
          ans = min(ans, abc);
        } else {
          if (arr[0] == arr[arr.size() - 1])
            ans = min(ans, abc + 1);
          else
            ans = min(ans, abc);
        }
      }
    }
    printf("%d\n", ans);
  }
}
