#include using namespace std; const int MaxN = (int)5e5 + 10; const int INF = (int)1e9; const int MOD = (int)1e9 + 7; int fenw[26]; void upd(int r, int val) { for (int i = r; i < 26; i |= i + 1) { fenw[i] += val; } } int get(int r) { int res = 0; for (int i = r; i >= 0; i &= i + 1, --i) { res += fenw[i]; } return res; } long long getVal(const string &s) { long long tot = 0; memset(fenw, 0, sizeof(fenw)); for (int i = 0; i < (int)s.length(); ++i) { tot += get(s[i] - 'a' - 1); upd(s[i] - 'a', +1); } return tot; } void solve() { string s; cin >> s; long long ans = getVal(s); vector v[26]; for (int i = 0; i < (int)s.length(); ++i) { v[s[i] - 'a'].push_back(i); } for (int it = 0; it < 26; ++it) { if (v[it].empty()) continue; { int i = *v[it].begin(); char ch = s[i]; for (int j = 0; j < 26; ++j) { s[i] = (char)(j + 'a'); ans = min(ans, abs(ch - s[i]) + getVal(s)); } s[i] = ch; } { int i = v[it].back(); char ch = s[i]; for (int j = 0; j < 26; ++j) { s[i] = (char)(j + 'a'); ans = min(ans, abs(ch - s[i]) + getVal(s)); } s[i] = ch; } } cout << ans << "\n"; } int main() { // freopen("input.txt", "r", stdin); int t; scanf("%d", &t); while (t --> 0) { solve(); } return 0; }