#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    string second;
    cin >> second;
    long freq[10];
    for (int i = 0; i < 10; i++) {
      freq[i] = 0;
    }
    for (long i = 0; i < second.length(); i++) {
      if (second[i] == '0') {
        freq[0]++;
      }
      if (second[i] == '1') {
        freq[1]++;
      }
      if (second[i] == '2') {
        freq[2]++;
      }
      if (second[i] == '3') {
        freq[3]++;
      }
      if (second[i] == '4') {
        freq[4]++;
      }
      if (second[i] == '5') {
        freq[5]++;
      }
      if (second[i] == '6') {
        freq[6]++;
      }
      if (second[i] == '7') {
        freq[7]++;
      }
      if (second[i] == '8') {
        freq[8]++;
      }
      if (second[i] == '9') {
        freq[9]++;
      }
    }
    long max_freq = 0;
    for (int i = 0; i < 10; i++) {
      if (freq[i] > max_freq) {
        max_freq = freq[i];
      }
    }
    long ans1;
    if (max_freq == 1) {
      ans1 = second.length() - 2;
    } else {
      ans1 = second.length() - max_freq;
    }
    char c[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    long max_moves = 0;
    for (int c1 = 0; c1 < 10; c1++) {
      for (int c2 = 0; c2 < 10; c2++) {
        if (c1 != c2) {
          char x1 = c[c1];
          char x2 = c[c2];
          bool current = 0;
          long len = 0;
          for (long i = 0; i < second.length(); i++) {
            if (current == 0) {
              if (second[i] == x1) {
                len++;
                current = !current;
              }
            } else {
              if (second[i] == x2) {
                len++;
                current = !current;
              }
            }
          }
          if (len > max_moves) {
            max_moves = len;
          }
        }
      }
    }
    if (max_moves % 2 != 0) {
      max_moves--;
    }
    long mov = second.length() - max_moves;
    if (second.length() == 2) {
      cout << 0 << endl;
    } else {
      cout << min(ans1, mov) << endl;
    }
  }
  return 0;
}
