#include <fstream>
#include <iostream>

#include <algorithm>
#include <array>
#include <bitset>
#include <complex>
#include <functional>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include <cassert>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>

#define all(container) (container).begin(), (container).end()
#define sz(container) static_cast<int>((container).size())

using namespace std;

class Solver {
public:
  void solve(istream& in, ostream& out) {
    out.precision(20);

    int tests;
    cin >> tests;
    for (int test = 1; test <= tests; test++) {
      solveOne(in, out);
    }
  }

private:
  void solveOne(istream& in, ostream& out) {
    const string t = "atcoder";

    string s;
    cin >> s;

    if (t < s) {
      out << 0 << endl;
      return;
    }

    string worst = s;
    sort(all(worst));
    reverse(all(worst));
    
    if (worst <= t) {
      out << -1 << endl;
      return;
    }

    int answer = sz(s);
    int n = sz(s);
    int m = min(sz(s), sz(t));
    for (int to = 0; to < m; to++) {
      for (int from = 0; from < n; from++) {
        swap(s[to], s[from]);
        if (t < s) {
          answer = min(answer, abs(to - from));
        }
        swap(s[to], s[from]);
      }
    }
    cout << answer << endl;
  }
};

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  Solver solver;
  solver.solve(cin, cout);

  return 0;
}

#include <bits/stdc++.h>
using namespace std;
int n, m;
string s, t="atcoder";
int solve(int w) {
	string p = s;
	int ans = 0;
	for (int i=0; i<w; ++i) {
		int ok = 0;
		for (int j=i; j<n; ++j) {
			if (p[j]==t[i]) {
				for (int k=j; k>i; --k) swap(p[k],p[k-1]);
				ans += j-i;
				ok = 1;
				break;
			}
		}
		if (!ok) return 100000;
	}
	for (int i=w; i<n; ++i) {
		auto tmp = p;
		for (int k=i; k>w; --k) swap(p[k],p[k-1]);
		if (p>t) return ans+i-w;
		p = tmp;
	}
	return 100000;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		cin >> s;
		n = s.size();
		m = t.size();
		int ans=1e9;
		for (int i=0; i<min(n,m-1); ++i) {
			ans = min(ans, solve(i));
		}
		if (ans>1000) ans=-1;
		cout << ans << endl;
	}
}