#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void permute(int L ,string B ,vector<string> &answer) { //L-1為要交換的位置
if (L == B.size()){
if (find(answer.begin() ,answer.end() ,B) == answer.end()) {
answer.push_back(B);
}
}
else {
for (int i=L-1 ; i<B.size() ; i++){
if (i>L-1 && B[i]==B[L-1]) {
continue;
}
swap(B[L-1] ,B[i]);
permute(L+1 ,B ,answer);
swap(B[L-1] ,B[i]);
}
}
}
bool customSort(const string &a ,const string &b) {
for (int i=0 ; i<a.size() ; i++) {
int com1=a[i] ,com2=b[i];
if (com1 >= 'A' && com1 <= 'Z') {
com1 = (com1-'A')*2 + 1;
}
else {
com1 = (com1-'a')*2 + 2;
}
if (com2 >= 'A' && com2 <= 'Z') {
com2 = (com2-'A')*2 + 1;
}
else {
com2 = (com2-'a')*2 + 2;
}
if (com1 != com2) {
return com1 < com2;
}
}
return false;
}
int main(void)
{
int times;
cin >> times;
for (int t=0 ; t<times ; t++){
string B;
cin >> B;
vector <string> answer;
permute(1 ,B ,answer);
sort(answer.begin() ,answer.end() ,customSort);
for (auto &b : answer) {
cout << b << endl;
}
}
}