After rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.

Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters). 

Errorgorn can change Anton's DNA into string b which must be a permutation of a. However, Anton's body can defend against this attack. In 1 second, his body can swap 2 adjacent characters of his DNA to transform it back to a. Anton's body is smart and will use the minimum number of moves.

To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string B. Can you help him?

Input

The first line of input contains a single integer t (1 ≤ t ≤ 100000) — the number of testcases.

The first and only line of each testcase contains 1 string a (1 ≤ |a| ≤ 100000). a consists of only the characters "A", "N", "O" and "T".

It is guaranteed that the sum of |a| over all testcases does not exceed 100000.

Output

For each testcase, print a single string, b. If there are multiple answers, you can output any one of them. b must be a permutation of the string a.

Example

Input


4
ANTON
NAAN
AAAAAA
OAANTTON


Output


NNOTA
AANN
AAAAAA
TNNTAOOA

Note

For the first testcase, it takes 7 seconds for Anton's body to transform NNOTA to ANTON: 

NNOTA → NNOAT → NNAOT → NANOT → NANTO → ANNTO → ANTNO → ANTON. 

Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.

For the second testcase, it takes 2 seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.

Difficulty: HARD
Tags: Constructive algorithms

String algorithms

Complete search

Mathematics

Data structures
Skill types: Data structures

Complete search

Starter code:

Solutions:
from collections import defaultdict
import itertools
import sys
input = sys.stdin.readline
t = int(input())
p = list('ANOT')
q = [0, 1, 2, 3]
d = dict()
for i in range(4):
	d[p[i]] = i
for _ in range(t):
	a = list(input().rstrip())
	n = len(a)
	cnt = [0] * 4
	x = [[0] * 4 for _ in range(4)]
	for i in range(len(a)):
		j = d[a[i]]
		cnt[j] += 1
		for k in range(4):
			if j ^ k:
				x[j][k] += cnt[k]
	m = -1
	for u in itertools.permutations(q):
		ok = set()
		now = 0
		for i in u:
			for j in range(4):
				if j in ok:
					now += x[j][i]
			ok.add(i)
		if m < now:
			m = now
			v = list(u)
	b = []
	for i in v:
		b.append(p[i] * cnt[d[p[i]]])
	print(''.join(b))


import os, sys
from io import BytesIO, IOBase
from collections import deque, Counter, defaultdict as dft
from heapq import heappop, heappush
from math import log, sqrt, factorial, cos, tan, sin, radians, log2, ceil, floor
from bisect import bisect, bisect_left, bisect_right
from decimal import *
import sys, threading
from itertools import permutations, combinations
from copy import deepcopy
input = sys.stdin.readline
ii = lambda : int(input())
si = lambda : input().rstrip()
mp = lambda : map(int, input().split())
ms = lambda : map(str, input().strip().split(' '))
ml = lambda : list(mp())
mf = lambda : map(float, input().split())
alphs = 'abcdefghijklmnopqrstuvwxyz'

def steps(s, t):

	def update(i, val):
		while i <= n:
			arr[i] += val
			i += i & -i

	def query(i):
		sm = 0
		while i > 0:
			sm += arr[i]
			i -= i & -i
		return sm
	n = len(s)
	arr = [0] * (n + 1)
	dct = dft(list)
	for i in range(n - 1, -1, -1):
		dct[t[i]].append(i + 1)
	count = 0
	for i in range(n):
		idx = dct[s[i]].pop()
		count += abs(i + 1 - (idx + i - query(idx)))
		update(idx, 1)
	return count

def solve():
	s = input()
	dct = Counter(s)
	mx = -1
	res = ''
	for ls in permutations(['A', 'N', 'T', 'O']):
		temp = ''
		for c in ls:
			temp += c * dct[c]
		count = steps(s, temp)
		if count > mx:
			mx = count
			res = temp
	print(res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
tc = 1
tc = ii()
for i in range(tc):
	solve()


import sys
input = sys.stdin.readline
print = lambda s: sys.stdout.write(s + '\n')
import itertools
import collections
perms = list(itertools.permutations(['A', 'N', 'O', 'T']))

class FenwickTree:

	def __init__(self, n):
		self.t = [0] * (n + 1)

	def update(self, i, x):
		i += 1
		while i < len(self.t):
			self.t[i] += x
			i += i & -i

	def query(self, r):
		ans = 0
		while r > 0:
			ans += self.t[r]
			r -= r & -r
		return ans
t = int(input())
for _ in range(t):
	s = input().rstrip()
	n = len(s)
	ctr = collections.Counter(s)
	ans = (float('-inf'), None)
	for perm in perms:
		curVal = 0
		curS = []
		firstIdx = {}
		for p in perm:
			startIdx = 0
			for x in curS:
				startIdx += len(x)
			firstIdx[p] = startIdx
			curS.append(p * ctr[p])
		curS = ''.join(curS)
		ft = FenwickTree(n)
		for (i, x) in enumerate(curS):
			ft.update(i, 1)
		for (i, x) in enumerate(s):
			curVal += ft.query(firstIdx[x])
			ft.update(firstIdx[x], -1)
		if curVal > ans[0]:
			ans = (curVal, curS)
	print(ans[1])


import sys
input = sys.stdin.readline
from itertools import permutations

def mergeSort(arr, left, right):
	inv_count = 0
	if left < right:
		mid = left + (right - left) // 2
		inv_count += mergeSort(arr, left, mid)
		inv_count += mergeSort(arr, mid + 1, right)
		inv_count += merge(arr, left, mid, right)
	return inv_count

def merge(arr, left, mid, right):
	inv_count = 0
	n1 = mid - left + 1
	n2 = right - mid
	l = [0] * n1
	r = [0] * n2
	for i in range(0, n1):
		l[i] = arr[left + i]
	for i in range(0, n2):
		r[i] = arr[mid + i + 1]
	i = 0
	j = 0
	k = left
	while i < n1 and j < n2:
		if l[i] < r[j]:
			arr[k] = l[i]
			i += 1
			k += 1
		else:
			arr[k] = r[j]
			j += 1
			k += 1
			inv_count += n1 - i
	while i < n1:
		arr[k] = l[i]
		i += 1
		k += 1
	while j < n2:
		arr[k] = r[j]
		j += 1
		k += 1
	return inv_count

def create_c(a, b):
	c = [0] * len(a)
	idx = {}
	positions = {}
	for i in range(len(b)):
		if b[i] in positions:
			positions[b[i]].append(i)
		else:
			positions[b[i]] = [i]
	for i in range(len(a)):
		if a[i] in idx:
			idx[a[i]] += 1
		else:
			idx[a[i]] = 0
		c[i] = positions[a[i]][idx[a[i]]]
	return c
for _ in range(int(input())):
	a = input().strip()
	if len(a) <= 2:
		print(a[::-1])
		continue
	counts = dict(zip('ANTO', [0] * 4))
	for i in a:
		counts[i] += 1
	best_perm = None
	best_perm_cost = -1
	for order in permutations('ANTO'):
		final_perm = ''.join([char * counts[char] for char in order])
		final_arr = create_c(a, final_perm)
		cost = mergeSort(final_arr, 0, len(final_arr) - 1)
		if cost > best_perm_cost:
			best_perm = final_perm
			best_perm_cost = cost
	print(best_perm)


import itertools
TC = int(input())
m = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
st = 'ANOT'
for cas in range(TC):
	s = input()
	arr = []
	for ch in s:
		arr.append(m[ch])
	cnt = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
	cnt1 = [0, 0, 0, 0]
	for i in arr:
		for j in range(4):
			cnt[j][i] += cnt1[j]
		cnt1[i] += 1
	val = -1
	best = []
	for perm in itertools.permutations([0, 1, 2, 3]):
		curr = 0
		for i in range(4):
			for j in range(i + 1, 4):
				curr += cnt[perm[j]][perm[i]]
		if curr > val:
			val = curr
			best = perm
	for i in range(4):
		for j in range(cnt1[best[i]]):
			print(st[best[i]], end='')
	print()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from itertools import permutations
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def merge(arr, temp, left, mid, right):
	inv_count = 0
	i = left
	j = mid
	k = left
	while i <= mid - 1 and j <= right:
		if arr[i] <= arr[j]:
			temp[k] = arr[i]
			k += 1
			i += 1
		else:
			temp[k] = arr[j]
			k += 1
			j += 1
			inv_count = inv_count + (mid - i)
	while i <= mid - 1:
		temp[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp[k] = arr[j]
		k += 1
		j += 1
	for i in range(left, right + 1, 1):
		arr[i] = temp[i]
	return inv_count

def _mergeSort(arr, temp, left, right):
	inv_count = 0
	if right > left:
		mid = int((right + left) / 2)
		inv_count = _mergeSort(arr, temp, left, mid)
		inv_count += _mergeSort(arr, temp, mid + 1, right)
		inv_count += merge(arr, temp, left, mid + 1, right)
	return inv_count

def countSwaps(arr, n):
	temp = [0 for i in range(n)]
	return _mergeSort(arr, temp, 0, n - 1)
for ik in range(int(input())):
	s = list(input())
	n = len(s)
	ind = defaultdict(int)
	c = defaultdict(int)
	for i in range(n - 1, -1, -1):
		c[s[i]] += 1
	ind = defaultdict(list)
	for i in range(n):
		ind[s[i]].append(i)

	def find(d, tr):
		tr = list(tr)
		fi = ''
		for i in tr:
			fi += i * c[i]
		ans = []
		for i in tr:
			for j in ind[i]:
				ans.append(j)
		return (countSwaps(ans, len(ans)), fi)
	perm = [''.join(p) for p in permutations('ANTO')]
	ans = (0, '')
	for i in perm:
		ans = max(ans, find(s, i))
	print(ans[1])


from bisect import bisect, bisect_left
from collections import *
from heapq import *
from math import gcd, ceil, sqrt, floor, inf, pi
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

def A(n):
	return [0] * n

def AI(n, x):
	return [x] * n

def A2(n, m):
	return [[0] * m for i in range(n)]

def G(n):
	return [[] for i in range(n)]

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

def popcnt(x):
	ans = 0
	while x:
		ans += 1
		x &= x - 1
	return ans

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class ST:

	def __init__(self, arr):
		n = len(arr)
		mx = n.bit_length()
		self.st = [[0] * mx for i in range(n)]
		for i in range(n):
			self.st[i][0] = arr[i]
		for j in range(1, mx):
			for i in range(n - (1 << j) + 1):
				self.st[i][j] = max(self.st[i][j - 1], self.st[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		if l > r:
			return -inf
		s = (r + 1 - l).bit_length() - 1
		return max(self.st[l][s], self.st[r - (1 << s) + 1][s])

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

class UF:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n
		self.size = AI(n, 1)
		self.edge = A(n)

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			self.edge[pu] += 1
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			self.edge[pu] += self.edge[pv] + 1
			self.size[pu] += self.size[pv]
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv
			self.edge[pv] += self.edge[pu] + 1
			self.size[pv] += self.size[pu]

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return flag

def dij(s, graph):
	d = AI(n, inf)
	d[s] = 0
	heap = [(0, s)]
	vis = A(n)
	while heap:
		(dis, u) = heappop(heap)
		if vis[u]:
			continue
		vis[u] = 1
		for (v, w) in graph[u]:
			if d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def bell(s, g):
	dis = AI(n, inf)
	dis[s] = 0
	for i in range(n - 1):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
	change = A(n)
	for i in range(n):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
				change[v] = 1
	return dis

def lcm(a, b):
	return a * b // gcd(a, b)

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

def RP(nums):
	n = len(nums)
	s = set(nums)
	d = {}
	for (i, k) in enumerate(sorted(s), 1):
		d[k] = i
	bi = BIT([0] * (len(s) + 1))
	ans = 0
	for i in range(n - 1, -1, -1):
		ans += bi.query(d[nums[i]] - 1)
		bi.update(d[nums[i]], 1)
	return ans

def michange(a, b):
	d = defaultdict(deque)
	for (i, x) in enumerate(b):
		d[x].append(i)
	order = A(len(a))
	for (i, x) in enumerate(a):
		if not d:
			return -1
		order[i] = d[x].popleft()
	return RP(order)

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j, n, m):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None
t = N()
for i in range(t):
	a = input()
	s = 'ANTO'
	n = len(a)
	ans = -1
	arr = None
	for r in permutations(range(4)):
		d = {}
		for i in range(4):
			d[s[i]] = r[i]
		cnt = A(4)
		res = 0
		for i in range(n):
			cur = d[a[i]]
			for j in range(cur + 1, 4):
				res += cnt[j]
			cnt[cur] += 1
		if res > ans:
			arr = r
			ans = res
	c = Counter(a)
	ans = ''
	tmp = [''] * 4
	for i in range(4):
		tmp[arr[i]] = s[i]
	for i in range(4):
		ans += tmp[i] * c[tmp[i]]
	print(ans)


class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

class OrderedList(SortedList):

	def __init__(self, arg):
		super().__init__(arg)

	def rangeCountByValue(self, leftVal, rightVal):
		leftCummulative = self.bisect_left(leftVal)
		rightCummulative = self.bisect_left(rightVal + 1)
		return rightCummulative - leftCummulative
from itertools import permutations

def getMinMoves(arr, s):
	n = len(s)
	charIndexes = dict()
	for i in range(n - 1, -1, -1):
		if s[i] not in charIndexes.keys():
			charIndexes[s[i]] = []
		charIndexes[s[i]].append(i)
	availableIdx = SortedList(list(range(n)))
	nMoves = 0
	for c in arr:
		i = charIndexes[c].pop()
		nMoves += availableIdx.bisect_left(i)
		availableIdx.remove(i)
	return nMoves

def main():
	n = int(input())
	allans = []
	for _ in range(n):
		s = input()
		chars = []
		charCnts = dict()
		for c in s:
			if c not in charCnts.keys():
				chars.append(c)
				charCnts[c] = 0
			charCnts[c] += 1
		currMax = -1
		ans = []
		for p in permutations(chars):
			arr = []
			for c in p:
				for __ in range(charCnts[c]):
					arr.append(c)
			nMoves = getMinMoves(arr, s)
			if nMoves > currMax:
				ans = arr
				currMax = nMoves
		allans.append(''.join(ans))
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


from itertools import permutations

class SegmentTree:

	def __init__(self, arr, func, initialRes=0):
		self.f = func
		self.N = len(arr)
		self.tree = [0 for _ in range(2 * self.N)]
		self.initialRes = initialRes
		for i in range(self.N):
			self.tree[self.N + i] = arr[i]
		for i in range(self.N - 1, 0, -1):
			self.tree[i] = self.f(self.tree[i << 1], self.tree[i << 1 | 1])

	def updateTreeNode(self, idx, value):
		self.tree[idx + self.N] = value
		idx += self.N
		i = idx
		while i > 1:
			self.tree[i >> 1] = self.f(self.tree[i], self.tree[i ^ 1])
			i >>= 1

	def query(self, l, r):
		r += 1
		res = self.initialRes
		l += self.N
		r += self.N
		while l < r:
			if l & 1:
				res = self.f(res, self.tree[l])
				l += 1
			if r & 1:
				r -= 1
				res = self.f(res, self.tree[r])
			l >>= 1
			r >>= 1
		return res

def getMaxSegTree(arr):
	return SegmentTree(arr, lambda a, b: max(a, b), initialRes=-float('inf'))

def getMinSegTree(arr):
	return SegmentTree(arr, lambda a, b: min(a, b), initialRes=float('inf'))

def getSumSegTree(arr):
	return SegmentTree(arr, lambda a, b: a + b, initialRes=0)

def getMinMoves(arr, s):
	n = len(s)
	charIndexes = dict()
	for i in range(n - 1, -1, -1):
		if s[i] not in charIndexes.keys():
			charIndexes[s[i]] = []
		charIndexes[s[i]].append(i)
	elmCnts = getSumSegTree([1] * n)
	nMoves = 0
	for c in arr:
		i = charIndexes[c].pop()
		nMoves += elmCnts.query(0, i) - 1
		elmCnts.updateTreeNode(i, 0)
	return nMoves

def main():
	n = int(input())
	allans = []
	for _ in range(n):
		s = input()
		chars = []
		charCnts = dict()
		for c in s:
			if c not in charCnts.keys():
				chars.append(c)
				charCnts[c] = 0
			charCnts[c] += 1
		currMax = -1
		ans = []
		for p in permutations(chars):
			arr = []
			for c in p:
				for __ in range(charCnts[c]):
					arr.append(c)
			nMoves = getMinMoves(arr, s)
			if nMoves > currMax:
				ans = arr
				currMax = nMoves
		allans.append(''.join(ans))
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import time
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def getInt():
	return int(input())

def getStrs():
	return input().split()

def getInts():
	return list(map(int, input().split()))

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def getBin():
	return list(map(int, list(input())))

def isInt(s):
	return '0' <= s[0] <= '9'

def ceil_(a, b):
	return (a + b - 1) // b
MOD = 10 ** 9 + 7
import itertools

def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] <= arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count
ops = list(range(4))
letters = ['A', 'N', 'T', 'O']

def solve():
	S = listStr()
	N = len(S)
	apps = [[] for _ in range(4)]
	for (i, s) in enumerate(S):
		if s == 'A':
			apps[0].append(i)
		elif s == 'N':
			apps[1].append(i)
		elif s == 'T':
			apps[2].append(i)
		else:
			apps[3].append(i)
	best = 0
	ans = S
	for perm in itertools.permutations(ops):
		tmp = []
		for i in range(4):
			tmp += apps[perm[i]]
		curr = mergeSort(tmp, N)
		if curr > best:
			best = curr
			ans = []
			for i in range(4):
				ans += [letters[perm[i]]] * len(apps[perm[i]])
	return ''.join(ans)
for _ in range(getInt()):
	print(solve())


from itertools import permutations
t = int(input())
perms = list(permutations(range(4)))

def inversion(d, L):
	if len(d) == 1:
		return ((g for g in d), 1, 0)
	(a, A, b) = inversion(d[:L // 2], L // 2)
	(c, C, e) = inversion(d[L // 2:], (L + 1) // 2)
	k = 0
	s = []
	a_ = next(a)
	c_ = next(c)
	while a_ != -1 != c_:
		if a_ < c_:
			s.append(a_)
			a_ = next(a, -1)
			A -= 1
		else:
			s.append(c_)
			c_ = next(c, -1)
			k += A
	while a_ != -1:
		s.append(a_)
		a_ = next(a, -1)
	while c_ != -1:
		s.append(c_)
		c_ = next(c, -1)
	return ((g for g in s), L, b + e + k)
for _ in range(t):
	s = input().strip()
	pos = [[], [], [], []]
	for (i, c) in enumerate(s):
		pos['ANTO'.index(c)].append(i)
	siz = [len(a) for a in pos]
	m = 0
	best = (0, 1, 2, 3)
	for k in perms:
		d = []
		for j in range(4):
			d += pos[k[j]]
		z = inversion(d, len(d))[2]
		if m < z:
			best = k
			m = z
	res = ''
	for x in best:
		res += 'ANTO'[x] * siz[x]
	print(res)


from itertools import permutations as per
from collections import Counter
for test in range(int(input())):
	s = input()
	mx = 0
	ms = {}
	cont = Counter(s)
	for d in ({'A': p[0], 'N': p[1], 'O': p[2], 'T': p[3]} for p in per([0, 1, 2, 3], 4)):
		cost = 0
		c = [0, 0, 0, 0]
		for i in cont.keys():
			c[d[i]] = cont[i]
		for i in s:
			cost += sum(c[:d[i]])
			c[d[i]] -= 1
		if cost > mx:
			ms = d
			mx = cost
	if ms == {}:
		print(s)
	else:
		t = sorted(list(ms.items()), key=lambda x: x[1])
		ans = ''
		for (n, i) in t:
			ans += n * cont[n]
		print(ans)


import io
import os
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from math import gcd, inf
import itertools

def solve(A):
	N = len(A)
	relabel = {'A': 0, 'N': 1, 'T': 2, 'O': 3}
	labelsA = [relabel[A[i]] for i in range(N)]
	pref = [[0] for i in range(4)]
	for i in labelsA:
		for j in range(4):
			pref[j].append(pref[j][-1] + (i == j))

	def getLess(i, pref):
		left = [pref[0][i], pref[1][i], pref[2][i], pref[3][i]]
		return left
	less1 = [[] for i in range(4)]
	for i in range(N):
		less1[labelsA[i]].append(getLess(i, pref))
	freqItems = Counter(labelsA).items()
	best = (0,)
	for perm in itertools.permutations(freqItems):
		labelsB = []
		for (k, v) in perm:
			labelsB.extend([k] * v)
		pref2 = [[0] for i in range(4)]
		for i in labelsB:
			for j in range(4):
				pref2[j].append(pref2[j][-1] + (i == j))
		less2 = [[] for i in range(4)]
		for i in range(N):
			less2[labelsB[i]].append(getLess(i, pref2))
		cost = 0
		for k in range(4):
			v1 = less1[k]
			v2 = less2[k]
			for (l1, l2) in zip(v1, v2):
				count = 0
				for (x, y) in zip(l1, l2):
					count += abs(x - y)
				cost += count
		best = max(best, (cost, labelsB))
	unlabel = 'ANTO'
	ret = ''.join((unlabel[i] for i in best[1]))
	return ret
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	A = input().decode().rstrip()
	ans = solve(A)
	print(ans)


from itertools import permutations

def f(pos, k):
	m = len(pos)
	(a1, a2) = ([0], [0])
	for i in range(m):
		a1.append(a1[-1] + pos[i] - i)
	for i in range(1, m + 1):
		a2.append(a2[-1] + k - i - pos[m - i])
	a2 = a2[::-1]
	ind = max(range(m + 1), key=lambda i: a1[i] + a2[i])
	return (ind, a1[ind] + a2[ind])

def solve(s):
	n = len(s)
	ma = -1
	ans = []
	for p in permutations(['A', 'N', 'O', 'T']):
		cur = 0
		(ans1, ans2) = ([], [])
		s1 = s[:]
		for c in p:
			s2 = []
			pos = []
			for i in range(len(s1)):
				if s1[i] == c:
					pos.append(i)
				else:
					s2.append(s1[i])
			(x, y) = f(pos, len(s1))
			cur += y
			ans1.extend([c] * x)
			ans2.extend([c] * (len(pos) - x))
			s1 = s2
		ans1.extend(ans2[::-1])
		if cur > ma:
			ma = cur
			ans = ans1
	return ''.join(ans)
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	s = list(input())
	print(solve(s))


import sys
input = sys.stdin.readline
from itertools import permutations

class bit:

	def __init__(self, n):
		self.n = n + 1
		self.a = [0] * self.n

	def add(self, idx, val):
		idx += 1
		while idx < self.n:
			self.a[idx] += val
			idx += idx & -idx

	def sum_prefix(self, idx):
		tot = 0
		idx += 1
		while idx > 0:
			tot += self.a[idx]
			idx -= idx & -idx
		return tot

def inversions(a):
	tot = 0
	loc = [0] * len(a)
	for i in range(len(a)):
		loc[a[i]] = i
	bt = bit(len(a))
	for i in range(len(a) - 1, -1, -1):
		tot += bt.sum_prefix(loc[i])
		bt.add(loc[i], 1)
	return tot

def create_c(a, b):
	c = [0] * len(a)
	idx = {}
	positions = {}
	for i in range(len(b)):
		if b[i] in positions:
			positions[b[i]].append(i)
		else:
			positions[b[i]] = [i]
	for i in range(len(a)):
		if a[i] in idx:
			idx[a[i]] += 1
		else:
			idx[a[i]] = 0
		c[i] = positions[a[i]][idx[a[i]]]
	return c
for _ in range(int(input())):
	a = input().strip()
	counts = dict(zip('ANTO', [0] * 4))
	for i in a:
		counts[i] += 1
	best_perm = None
	best_perm_cost = -1
	for order in permutations('ANTO'):
		final_perm = ''.join([char * counts[char] for char in order])
		cost = inversions(create_c(a, final_perm))
		if cost > best_perm_cost:
			best_perm = final_perm
			best_perm_cost = cost
	print(best_perm)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from itertools import permutations as p
from collections import defaultdict as dd
for t in range(int(input())):
	s = input()
	l = set(s)
	l1 = [i for i in p(l)]
	d = dd(list)
	n = len(s)
	for i in range(n):
		d[s[i]].append(i)
	c = 0
	ans = l.copy()
	for i in l1:
		x = 0
		d1 = dd(int)
		sh = dd(int)
		for j in i:
			d1[j] = x
			x += len(d[j])
		x = 0
		a = 0
		for j in s:
			x += d1[j] + sh[j] - a
			a += 1
			d1[j] += 1
			for k in i:
				if k == j:
					break
				sh[k] += 1
		if x > c:
			c = x
			ans = list(i)
	ansf = []
	for i in ans:
		ansf.append(i * len(d[i]))
	print(''.join(ansf))


import itertools
from collections import Counter

def readline():
	return map(int, input().split())

def solve():
	s = input()
	total = Counter()
	p = Counter()
	letters = set(s)
	for a in s:
		total[a] += 1
		for b in letters:
			if b != a:
				p[b + a] += total[b]

	def score(perm):
		return sum((p[b + a] for (i, a) in enumerate(perm) for b in perm[i + 1:]))
	winner = max(itertools.permutations(letters), key=score)
	print(''.join((a * total[a] for a in winner)))

def main():
	t = int(input())
	for __ in range(t):
		solve()
main()


from collections import defaultdict, Counter
from math import sqrt, log10, log2, log, gcd, ceil, floor
from bisect import bisect_left, bisect_right
from itertools import permutations
import sys, io, os
input = sys.stdin.readline
sys.setrecursionlimit(10000)

def get_list():
	return [int(i) for i in input().split()]
inf = float('inf')
t = 1

def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] <= arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count

def respect(a, b):
	n = len(b)
	indices = defaultdict(list)
	ans = [0] * n
	for i in range(n):
		indices[b[i]].append(i + 1)
	for i in indices:
		indices[i].reverse()
	for i in range(n):
		ans[i] = indices[a[i]].pop()
	return ans
char = list('ANOT')
permutat = [i for i in permutations(char)]

def all(dict):
	newl = set()
	l = []
	for i in permutat:
		l = []
		for j in i:
			l += [j] * dict[j]
		newl.add(''.join(l))
	return newl
for i in range(int(input())):
	s = list(input().strip())
	n = len(s)
	dict = Counter(s)
	l = all(dict)
	maxinversion = -inf
	ans = ''
	for i in l:
		arr = respect(i, s)
		inversion = mergeSort(arr, n)
		if maxinversion < inversion:
			maxinversion = inversion
			ans = i
	print(ans)


from sys import stdin
from itertools import permutations
input = stdin.readline
global T, N
d = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
rd = {0: 'A', 1: 'N', 2: 'O', 3: 'T'}

def read(index):
	global T, N
	s = 0
	while index > 0:
		s += T[index]
		index -= index & -index
	return s

def update(index, val):
	global T, N
	while index <= N:
		T[index] += val
		index += index & -index
for t in range(int(input())):
	S = input().rstrip()
	N = len(S)
	groups = [0, 0, 0, 0]
	A = [[] for _ in range(4)]
	for i in range(N):
		ind = d[S[i]]
		A[ind].append(i + 1)
		groups[ind] += 1
	mx = -1
	s = ''
	for perm in permutations([0, 1, 2, 3]):
		(a, n, o, t) = perm
		S = ''
		for i in perm:
			S += rd[i] * groups[i]
		inds = [-1 for _ in range(4)]
		T = [0 for _ in range(N + 1)]
		ans = 0
		for i in range(N - 1, -1, -1):
			idx = d[S[i]]
			x = A[idx][inds[idx]]
			inds[idx] -= 1
			ans += i + 1 - x - read(x)
			update(x + 1, -1)
		if ans > mx:
			s = S
			mx = ans
	print(s)


from sys import stdin, stdout
from itertools import permutations
dic = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
dic2 = {0: 'A', 1: 'N', 2: 'O', 3: 'T'}

def kill_anton(a):
	global dic
	cnta1 = [[0 for _ in range(4)] for _ in range(4)]
	cnta2 = [0 for _ in range(4)]
	for c in a:
		for i in range(4):
			cnta1[dic[c]][i] += cnta2[i]
		cnta2[dic[c]] += 1
	rmoves = 0
	rperm = [0, 1, 2, 3]
	for perm in permutations([0, 1, 2, 3]):
		moves = 0
		for i in range(4):
			for j in range(i + 1, 4):
				moves += cnta1[perm[i]][perm[j]]
		if moves > rmoves:
			rmoves = moves
			rperm = perm
	r = ''
	for p in rperm:
		r += dic2[p] * cnta2[p]
	return r
t = int(stdin.readline())
for _ in range(t):
	a = stdin.readline().strip()
	r = kill_anton(a)
	stdout.write(r + '\n')


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations, combinations

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = int(1000000000.0) + 7
for t in range(int(data())):
	a = data()
	m = [[0] * 26 for i in range(26)]
	d = dd(int)
	for i in a:
		s = ord(i) - 65
		for j in range(26):
			if s != j:
				m[s][j] += m[j][j]
		m[s][s] += 1
		d[i] += 1
	l1 = sorted(d.keys())
	total = 0
	ans = l1
	for l in permutations(l1):
		total1 = 0
		for i in range(len(l) - 1):
			s1 = ord(l[i]) - 65
			for j in range(i + 1, len(l)):
				s2 = ord(l[j]) - 65
				total1 += m[s1][s2]
		if total1 > total:
			total = total1
			ans = l
	ans1 = ''
	for i in ans:
		ans1 += i * d[i]
	out(ans1)


import sys
from sys import stdin
import itertools
tt = int(stdin.readline())
alp = 'ANTO'
dic = {}
dic['A'] = 0
dic['N'] = 1
dic['T'] = 2
dic['O'] = 3
ANS = []
for loop in range(tt):
	s = stdin.readline()[:-1]
	lis = [[0] * 4 for i in range(4)]
	num = [0] * 4
	for tmp in s:
		i = dic[tmp]
		for j in range(4):
			if i != j:
				lis[j][i] += num[j]
		num[i] += 1
	ans = -1
	maxp = 0
	for p in itertools.permutations((0, 1, 2, 3)):
		np = list(p)
		nans = 0
		for ri in range(4):
			for li in range(ri):
				l = np[li]
				r = np[ri]
				nans += lis[r][l]
		if ans < nans:
			ans = nans
			maxp = np
	astr = []
	for i in maxp:
		astr.append(alp[i] * num[i])
	ANS.append(''.join(astr))
print('\n'.join(ANS))


import sys
input = sys.stdin.readline
print = lambda s: sys.stdout.write(s + '\n')
import itertools
import collections
perms = list(itertools.permutations(['A', 'N', 'O', 'T']))
mp = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
rmp = 'ANOT'
t = int(input())
for _ in range(t):
	s = input().rstrip()
	n = len(s)
	s = list(map(lambda x: mp[x], s))
	cnt = collections.Counter()
	befCnt = [[0] * 4 for j in range(4)]
	for i in s:
		for j in range(4):
			befCnt[j][i] += cnt[j]
		cnt[i] += 1
	best = (float('-inf'), [])
	for perm in itertools.permutations([0, 1, 2, 3]):
		cur = 0
		for (i, x) in enumerate(perm):
			for j in range(i + 1, 4):
				cur += befCnt[perm[j]][x]
		if cur > best[0]:
			best = (cur, perm)
	print(''.join(map(lambda x: rmp[x] * cnt[x], best[1])))


from itertools import permutations as p
from collections import Counter, defaultdict as dd
from sys import stdin, stdout
inp = stdin.readline
for t in range(int(inp())):
	s = inp().rstrip('\n')
	l = set(s)
	l1 = [i for i in p(l)]
	d = Counter(s)
	c = 0
	ans = l.copy()
	for i in l1:
		x = 0
		d1 = dd(int)
		sh = dd(int)
		for j in i:
			d1[j] = x
			x += d[j]
		x = 0
		a = 0
		for j in s:
			x += d1[j] + sh[j] - a
			a += 1
			d1[j] += 1
			for k in i:
				if k == j:
					break
				sh[k] += 1
		if x > c:
			c = x
			ans = list(i)
	ansf = []
	for i in ans:
		ansf.append(i * d[i])
	stdout.write(''.join(ansf) + '\n')


from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))
(graph, mod, szzz) = ({}, 10 ** 9 + 7, lambda : sorted(zzz()))

def getStr():
	return input()

def getInt():
	return int(input())

def listStr():
	return list(input())

def getStrs():
	return input().split()

def isInt(s):
	return '0' <= s[0] <= '9'

def input():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in input().split()]

def output(answer, end='\n'):
	stdout.write(str(answer) + end)

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
num = getInt()
m = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
st = 'ANOT'
for _ in range(num):
	s = getStr()
	arr = []
	for ch in s:
		arr.append(m[ch])
	cnt = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
	cnt1 = [0, 0, 0, 0]
	for i in arr:
		for j in range(4):
			cnt[j][i] += cnt1[j]
		cnt1[i] += 1
	val = -1
	best = []
	for perm in permutations([0, 1, 2, 3]):
		curr = 0
		for i in range(4):
			for j in range(i + 1, 4):
				curr += cnt[perm[j]][perm[i]]
		if curr > val:
			val = curr
			best = perm
	for i in range(4):
		for j in range(cnt1[best[i]]):
			print(st[best[i]], end='')
	print()


import sys, io, os
try:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
except:
	input = lambda : sys.stdin.readline().encode()
read = lambda : map(int, input().split())
import itertools
L = list(itertools.permutations(range(4)))

def sol(s):
	c = [0] * 4
	d = [[0] * 4 for i in range(3)]
	R = []
	for i in s:
		c[i] += 1
		if i == 3:
			d[0][3] += c[0]
			d[1][3] += c[1]
			d[2][3] += c[2]
		elif i == 2:
			d[0][2] += c[0]
			d[1][2] += c[1]
		elif i == 1:
			d[0][1] += c[0]
	m = -1
	for i in L:
		t = 0
		for x in range(4):
			for y in range(x):
				(v, w) = (i[y], i[x])
				if v < w:
					t += c[v] * c[w] - d[v][w]
				else:
					t += d[w][v]
		if t > m:
			m = t
			P = i
	for w in P:
		R.append('TANO'[w] * int(c[w]))
	return ''.join(R)
out = []
for _ in range(int(input())):
	s = list(map(lambda x: x % 4, input().strip()))
	out.append(sol(s))
print('\n'.join(out))


import sys, os, io
input = sys.stdin.readline
from itertools import permutations

def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] <= arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count
for i in range(int(input())):
	s = input().strip()
	n = len(s)
	a = [0] * n
	for i in range(len(s)):
		if s[i] == 'A':
			a[i] = 0
		elif s[i] == 'N':
			a[i] = 1
		elif s[i] == 'T':
			a[i] = 2
		else:
			a[i] = 3
	cnt = [0] * 26
	for i in a:
		cnt[i] += 1
	p = [0, 1, 2, 3]
	ans = 0
	ansa = []
	for i in permutations(p):
		na = [0] * n
		ii = 0
		ind = [[] for i in range(4)]
		for j in i:
			for k in range(cnt[j]):
				na[ii] = j
				ii += 1
				ind[j].append(ii)
		for i in range(4):
			ind[i].reverse()
		b = []
		for i in a:
			b.append(ind[i].pop())
		tans = mergeSort(b, n)
		if tans >= ans:
			ans = tans
			ansa = na[:]
	for i in ansa:
		if i == 0:
			print('A', end='')
		elif i == 1:
			print('N', end='')
		elif i == 2:
			print('T', end='')
		else:
			print('O', end='')
	print()


import sys
from itertools import permutations

def I():
	return int(sys.stdin.readline().rstrip())

def MI():
	return map(int, sys.stdin.readline().rstrip().split())

def LI():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def LI2():
	return list(map(int, sys.stdin.readline().rstrip()))

def S():
	return sys.stdin.readline().rstrip()

def LS():
	return list(sys.stdin.readline().rstrip().split())

def LS2():
	return list(sys.stdin.readline().rstrip())
t = I()
C = ['A', 'N', 'T', 'O']
for _ in range(t):
	X = S()
	count1 = [0] * 4
	count2 = [[0] * 4 for _ in range(4)]
	for x in X:
		if x == 'A':
			count1[0] += 1
			for i in range(4):
				if i == 0:
					continue
				count2[i][0] += count1[i]
		elif x == 'N':
			count1[1] += 1
			for i in range(4):
				if i == 1:
					continue
				count2[i][1] += count1[i]
		elif x == 'T':
			count1[2] += 1
			for i in range(4):
				if i == 2:
					continue
				count2[i][2] += count1[i]
		else:
			count1[3] += 1
			for i in range(4):
				if i == 3:
					continue
				count2[i][3] += count1[i]
	M = -1
	ans = (0, 0, 0, 0)
	for A in list(permutations([0, 1, 2, 3], 4)):
		cnt = 0
		for i in range(4):
			a = A[i]
			for j in range(i + 1, 4):
				b = A[j]
				cnt += count2[b][a]
		if M < cnt:
			M = cnt
			ans = A
	ANS = [C[ans[0]]] * count1[ans[0]] + [C[ans[1]]] * count1[ans[1]] + [C[ans[2]]] * count1[ans[2]] + [C[ans[3]]] * count1[ans[3]]
	ANS = ''.join(ANS)
	print(ANS)


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	if n == 1:
		return 0
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [digit[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [digit[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n, mod=0):
		self.BIT = [0] * (n + 1)
		self.num = n
		self.mod = mod

	def query(self, idx):
		res_sum = 0
		mod = self.mod
		while idx > 0:
			res_sum += self.BIT[idx]
			if mod:
				res_sum %= mod
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		mod = self.mod
		while idx <= self.num:
			self.BIT[idx] += x
			if mod:
				self.BIT[idx] %= mod
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class Matrix:
	mod = 10 ** 9 + 7

	def set_mod(m):
		Matrix.mod = m

	def __init__(self, L):
		self.row = len(L)
		self.column = len(L[0])
		self._matrix = L
		for i in range(self.row):
			for j in range(self.column):
				self._matridigit[i][j] %= Matrix.mod

	def __getitem__(self, item):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		return self._matridigit[i][j]

	def __setitem__(self, item, val):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		self._matridigit[i][j] = val

	def __add__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matridigit[i][j] + other._matridigit[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __sub__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matridigit[i][j] - other._matridigit[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __mul__(self, other):
		if type(other) != int:
			if self.column != other.row:
				raise SizeError('sizes of matrixes are different')
			res = [[0 for j in range(other.column)] for i in range(self.row)]
			for i in range(self.row):
				for j in range(other.column):
					temp = 0
					for k in range(self.column):
						temp += self._matridigit[i][k] * other._matrix[k][j]
					res[i][j] = temp % Matrix.mod
			return Matrix(res)
		else:
			n = other
			res = [[n * self._matridigit[i][j] % Matrix.mod for j in range(self.column)] for i in range(self.row)]
			return Matrix(res)

	def __pow__(self, m):
		if self.column != self.row:
			raise MatrixPowError('the size of row must be the same as that of column')
		n = self.row
		res = Matrix([[int(i == j) for i in range(n)] for j in range(n)])
		while m:
			if m % 2 == 1:
				res = res * self
			self = self * self
			m //= 2
		return res

	def __str__(self):
		res = []
		for i in range(self.row):
			for j in range(self.column):
				res.append(str(self._matridigit[i][j]))
				res.append(' ')
			res.append('\n')
		res = res[:len(res) - 1]
		return ''.join(res)
from collections import deque

class Dinic:

	def __init__(self, N):
		self.N = N
		self.G = [[] for i in range(N)]

	def add_edge(self, fr, to, cap):
		forward = [to, cap, None]
		forward[2] = backward = [fr, 0, forward]
		self.G[fr].append(forward)
		self.G[to].append(backward)

	def add_multi_edge(self, v1, v2, cap1, cap2):
		edge1 = [v2, cap1, None]
		edge1[2] = edge2 = [v1, cap2, edge1]
		self.G[v1].append(edge1)
		self.G[v2].append(edge2)

	def bfs(self, s, t):
		self.level = level = [None] * self.N
		deq = deque([s])
		level[s] = 0
		G = self.G
		while deq:
			v = deq.popleft()
			lv = level[v] + 1
			for (w, cap, _) in G[v]:
				if cap and level[w] is None:
					level[w] = lv
					deq.append(w)
		return level[t] is not None

	def dfs(self, v, t, f):
		if v == t:
			return f
		level = self.level
		for e in self.it[v]:
			(w, cap, rev) = e
			if cap and level[v] < level[w]:
				d = self.dfs(w, t, min(f, cap))
				if d:
					e[1] -= d
					rev[1] += d
					return d
		return 0

	def flow(self, s, t):
		flow = 0
		INF = 10 ** 9 + 7
		G = self.G
		while self.bfs(s, t):
			(*self.it,) = map(iter, self.G)
			f = INF
			while f:
				f = self.dfs(s, t, INF)
				flow += f
		return flow

class SegmentTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		self.size = n
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			k >>= 1
			self.tree[k] = self.segfunc(self.tree[2 * k], self.tree[2 * k + 1])

	def query(self, l, r):
		if r == self.size:
			r = self.num
		res = self.ide_ele
		l += self.num
		r += self.num
		right = []
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				right.append(self.tree[r - 1])
			l >>= 1
			r >>= 1
		for y in right[::-1]:
			res = self.segfunc(res, y)
		return res
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.readline().rstrip()
mi = lambda : map(int, input().split())
li = lambda : list(mi())

def compare(N, A, B):
	cnt = [0 for i in range(N)]
	for b in B:
		cnt[b] += 1
	for i in range(1, N):
		cnt[i] += cnt[i - 1]
	t1 = 0
	t2 = 0
	for a in A:
		t1 += cnt[a]
		t2 += len(B) - cnt[a]
	return (t1, t2)
c = 'ANTO'
for _ in range(int(input())):
	s = input()
	(A, N, T, O) = ([], [], [], [])
	n = len(s)
	for i in range(len(s)):
		if s[i] == 'A':
			A.append(i)
		elif s[i] == 'N':
			N.append(i)
		elif s[i] == 'T':
			T.append(i)
		else:
			O.append(i)
	data = [A, N, T, O]
	t = [[0 for j in range(4)] for i in range(4)]
	for i in range(4):
		for j in range(i + 1, 4):
			(t1, t2) = compare(n, data[i], data[j])
			t[i][j] = t1
			t[j][i] = t2
	L = permutations([i for i in range(4)])
	ans = None
	val = -1
	for p in L:
		p = tuple(p)
		tmp = 0
		for i in range(4):
			for j in range(i + 1, 4):
				tmp += t[p[i]][p[j]]
		if tmp > val:
			ans = p
			val = tmp
	res = []
	for i in range(4):
		res += [c[ans[i]]] * len(data[ans[i]])
	print(''.join(res))


from sys import stdin, stdout
import heapq
from collections import defaultdict
import math
import bisect
import io, os
import itertools

def main():
	t = int(stdin.readline())
	rev = 'ANTO'
	for _ in range(t):
		s = stdin.readline().strip()
		cnt = [0] * 4
		cnt_perm = [[0] * 4 for _ in range(4)]
		for x in s:
			if x == 'A':
				x = 0
			elif x == 'N':
				x = 1
			elif x == 'T':
				x = 2
			else:
				x = 3
			for y in range(4):
				cnt_perm[y][x] += cnt[y]
			cnt[x] += 1
		mx = -1
		best = []
		for perm in itertools.permutations([0, 1, 2, 3]):
			cur = 0
			for i in range(4):
				for j in range(i + 1, 4):
					cur += cnt_perm[perm[j]][perm[i]]
			if cur > mx:
				mx = cur
				best = perm
		ans = ''
		for x in best:
			ans = ans + rev[x] * cnt[x]
		stdout.write(ans + '\n')
main()


import sys
import getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
(yes, no) = ('YES', 'NO')
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def minus_one(arr):
	return [x - 1 for x in arr]

def minus_one_matrix(mrr):
	return [[x - 1 for x in row] for row in mrr]

class FenwickTree:

	def __init__(self, bits=31):
		self.c = defaultdict(int)
		self.LARGE = 2 ** bits

	def update(self, x, increment):
		x += 1
		while x <= self.LARGE:
			self.c[x] += increment
			x += x & -x

	def query(self, x):
		x += 1
		res = 0
		while x > 0:
			res += self.c[x]
			x -= x & -x
		return res

def count_inversions(perm):
	res = 0
	t = FenwickTree(bits=len(bin(max(perm))))
	for (i, x) in enumerate(perm):
		cnt = t.query(x)
		res += i - cnt
		t.update(x, 1)
	return res

def solve_(srr):
	if len(srr) == 1:
		return srr
	c1 = defaultdict(list)
	for (i, x) in enumerate(srr):
		c1[x].append(i)
	c = Counter(srr)
	maxval = -1
	maxres = None
	for comb in itertools.permutations(c.keys()):
		locs = []
		for k in comb:
			locs.extend(c1[k])
		val = count_inversions(locs)
		if val > maxval:
			maxval = val
			maxres = comb
	log(maxval)
	trr = ''
	for k in maxres:
		trr += k * len(c1[k])
	return trr
for case_num in range(int(input())):
	srr = input().strip()
	res = solve(srr)
	print(res)


import itertools, sys
TC = int(input())
m = {'A': 0, 'N': 1, 'O': 2, 'T': 3}
st = 'ANOT'
for _ in range(TC):
	s = input()
	a = []
	for i in s:
		a.append(m[i])
	flips = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
	cnt = [0, 0, 0, 0]
	for i in a:
		for j in range(4):
			flips[j][i] += cnt[j]
		cnt[i] += 1
	best = []
	mx = -1
	for perm in itertools.permutations([0, 1, 2, 3]):
		c = 0
		for i in range(4):
			for j in range(i + 1, 4):
				c += flips[perm[j]][perm[i]]
		if c > mx:
			mx = c
			best = perm
	for i in range(4):
		for j in range(cnt[best[i]]):
			print(st[best[i]], end='')
	print()


import itertools
import sys
IS_INTERACTIVE = False
input = input
if not IS_INTERACTIVE:
	(*data,) = sys.stdin.read().split('\n')[::-1]

	def input():
		return data.pop()

def fprint(*args, **kwargs):
	print(*args, **kwargs, flush=True)

def eprint(*args, **kwargs):
	print(*args, **kwargs, file=sys.stderr)

def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] <= arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count

def calc_invs(a, priorities):
	a = [priorities[ch] for ch in a]
	return mergeSort(a, len(a))
for _ in range(int(input())):
	s = input()
	stat = {}
	for ch in 'ANTO':
		stat[ch] = s.count(ch)
	mx = 0
	mx_ans = s
	results = {}
	for perm in itertools.permutations('ANTO'):
		ans = []
		for ch in perm:
			ans.append(ch * stat[ch])
		ans = ''.join(ans)
		invs = calc_invs(s, {ch: i for (i, ch) in enumerate(perm)})
		if invs > mx:
			mx_ans = ans
			mx = invs
	print(mx_ans)


import sys
input = sys.stdin.readline
from collections import Counter, deque, defaultdict
from itertools import permutations

class Fenwick:

	def __init__(self, n):
		self.tree = [0] * (n + 1)
		self.n = n

	def update(self, x, val):
		while x <= self.n:
			self.tree[x] += val
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.tree[x]
			x -= x & -x
		return ans
for _ in range(int(input())):
	s = input()[:-1]
	n = len(s)
	cand = set(s)
	m = len(cand)
	cnt = Counter(s)
	ans = -1
	for idx in permutations(cand):
		cur = ''
		for x in idx:
			cur += x * cnt[x]
		dic = defaultdict(deque)
		for (i, c) in enumerate(s, 1):
			dic[c].append(i)
		A = []
		for c in cur:
			A.append(dic[c].popleft())
		bit = Fenwick(n)
		tot = 0
		for a in A:
			tot += bit.query(n) - bit.query(a)
			bit.update(a, 1)
		if tot > ans:
			ans = tot
			P = cur
	print(P)


import sys
input = lambda : sys.stdin.readline().rstrip()
from itertools import permutations

class BIT:

	def __init__(self, init):
		if type(init) == int:
			self.n = init + 1
			self.X = [0] * self.n
		else:
			self.n = len(init) + 1
			self.X = [0] + init
			for i in range(1, self.n):
				if i + (i & -i) < self.n:
					self.X[i + (i & -i)] += self.X[i]

	def add(self, i, x=1):
		i += 1
		while i < self.n:
			self.X[i] += x
			i += i & -i

	def getsum(self, i):
		ret = 0
		while i != 0:
			ret += self.X[i]
			i -= i & -i
		return ret

	def getrange(self, l, r):
		return self.getsum(r) - self.getsum(l)

def inversion_number(L):
	bit = BIT(len(L))
	ret = 0
	for (i, a) in enumerate(L):
		ret += i - bit.getsum(a + 1)
		bit.add(a)
	return ret

def inversion_number(L):
	ll = sorted(list(set(L)))
	dd = {a: i for (i, a) in enumerate(ll)}
	nL = [dd[l] for l in L]
	bit = BIT(len(nL))
	ret = 0
	for (i, a) in enumerate(nL):
		ret += i - bit.getsum(a + 1)
		bit.add(a)
	return ret

def calc(A):
	n = len(A)
	C = [0] * 4
	for a in A:
		C[a] += 1
	ma = 0
	pma = [0, 1, 2, 3]
	for p in permutations([0, 1, 2, 3]):
		D = [0] * 4
		c = 0
		for (i, a) in enumerate(p):
			D[a] = c
			c += C[a]
		B = [0] * n
		for (i, a) in enumerate(A):
			B[i] = D[a]
			D[a] += 1
		ivn = inversion_number(B)
		if ivn > ma:
			ma = ivn
			pma = p
	re = []
	for a in pma:
		re.append('ANTO'[a] * C[a])
	return ''.join(re)
T = int(input())
for _ in range(T):
	A = [0 if a == 'A' else 1 if a == 'N' else 2 if a == 'T' else 3 for a in input()]
	print(calc(A))