#include using namespace std; const int MAXN = (int) 1e5 + 10; int sum_n = 0; string str; void read() { cin >> str; int n = str.size(); assert(n >= 1 && n <= 100000); sum_n += n; for (int i = 0; i < n; i++) { assert(str[i] >= 'a' && str[i] <= 'z'); } } string construct(vector > a) { string ans = ""; // first put all characters having maximum number of occurences. if (a.size() > 0) { for (int i = 0; i < a[0].first; i++) { ans += a[0].second + 'a'; } } //cur_bad denoes number of bad spaces. int curbad = str.size(); for (int it = 1; it < a.size(); it++) { char ch = a[it].second + 'a'; int cnt = a[it].first; // try decreasing bad spaces string new_ans = ""; if (ans.size() > 0) { new_ans += ans[0]; } int bad = 0; for (int i = 1; i < ans.size(); i++) { if (ans[i] == ans[i - 1] && cnt > 0) { new_ans += ch; cnt--; } if (ans[i] == ans[i - 1]) { bad++; } new_ans += ans[i]; } assert(bad <= curbad); curbad = bad; string final_answer = new_ans; if (cnt > 0) { string copy = new_ans; new_ans = ""; new_ans += ch; new_ans += copy; final_answer = ""; cnt--; for (int i = 0; i < new_ans.size(); i++) { final_answer += new_ans[i]; if (new_ans[i] == ch || (i + 1 < new_ans.size() && new_ans[i + 1] == ch)) { continue; } if (cnt > 0) { final_answer += ch; cnt--; } } } ans = final_answer; } return ans; } // checks whether the all the characters of string s are rearranged properly or not int checkValidity(string s, vector > a) { vector cnt(26); for (int i = 0; i < a.size(); i++) { cnt[a[i].second] = a[i].first; } vector his_cnt(26); for (int i = 0; i < s.size(); i++) { his_cnt[s[i] - 'a']++; } for (int i = 0; i < 26; i++) { if (cnt[i] != his_cnt[i]) { return false; } } return true; } void work() { vector cnt(26); for (int i = 0; i < str.size(); i++) { cnt[str[i] - 'a']++; } vector > a; for (int i = 0; i < 26; i++) { if (cnt[i] > 0) { a.push_back(make_pair(cnt[i], i)); } } sort(a.rbegin(), a.rend()); int ok = true; for (int it = 0; it < a.size(); it++) { if (a[it].first > (str.size() + 1) / 2) { ok = false; } } if (ok) { string ans = construct(a); assert(checkValidity(ans, a)); cout << ans << endl; } else { cout << -1 << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; assert(T >= 1 && T <= 100000); while (T--) { read(); work(); } assert(sum_n >=1 && sum_n <= (int) 1e6); return 0; }