#include <bits/stdc++.h>
using namespace std;
int f(char s) { return (int)(s - '0'); }
int solve() {
  string s;
  cin >> s;
  int a[10][10], count[10][10];
  for (int i = 0; i <= 9; i++) {
    for (int j = 0; j <= 9; j++) {
      a[i][j] = 0;
      count[i][j] = 0;
    }
  }
  for (int i = 0; i < int((s).size()); i++) {
    for (int j = 0; j <= 9; j++) {
      if (f(s[i]) == j) {
        if (count[f(s[i])][j] == 0) {
          count[f(s[i])][j] = 1;
          a[j][j]++;
        } else {
          count[f(s[i])][j] = 0;
          a[j][j]++;
        }
        continue;
      }
      if (count[f(s[i])][j] == 0) {
        count[f(s[i])][j] = 1;
      }
      if (count[j][f(s[i])] == 1) {
        count[j][f(s[i])] = 0;
        a[j][f(s[i])] += 2;
      }
    }
  }
  int mx = 0;
  for (int i = 0; i <= 9; i++) {
    for (int j = 0; j <= 9; j++) {
      if (a[i][j] > mx) mx = a[i][j];
    }
  }
  cout << int((s).size()) - mx << "\n";
  return 0;
}
int main() {
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
