You have a string S consisting of N uppercase English letters. You are allowed to perform at most one operation of following kind: Choose any position in the string, remove the character at that position and insert it back to any other place in the string.

Find the  lexicographically smallest  string you can achieve.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains the single integer N denoting length of string S.
The second line contains the string S.

-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.

-----Constraints-----
- 1 ≤ T ≤ 50
- 1 ≤ N ≤ 50
- S will consist of uppercase English letters.

-----Example-----
Input:
2
4
DCBA
7
XYZZYZZ

Output:
ADCB
XYYZZZZ

-----Explanation-----
Example case 1. The optimal solution here is to choose the last character and put it in the beginning of the string. So the answer will be ADCB
Example case 2. The optimal solution here is to choose the 5-th character (1-based index) and put it between the 2-nd and the 3-rd characters. So the answer will be XYYZZZZ

Source: codechef | Difficulty: MEDIUM_HARD
Tags: String algorithms

Data structures

Complete search


Solutions:
def rightShift(s, i, j):
	s = list(s)
	while j > i:
		(s[j], s[j - 1]) = (s[j - 1], s[j])
		j -= 1
	return ''.join(s)

def leftShift(s, i, j):
	s = list(s)
	while j > i:
		(s[i], s[i + 1]) = (s[i + 1], s[i])
		i += 1
	return ''.join(s)

def solution():
	N = int(input())
	S = input()
	ans = S
	for i in range(N):
		for j in range(N):
			ls = leftShift(S, i, j)
			rs = rightShift(S, i, j)
			ans = min(ans, rs, ls)
	print(ans)
T = int(input())
while T > 0:
	T = T - 1
	solution()


t = int(input())
for i in range(t):
	n = int(input())
	s = input().upper()
	ans = 's'
	for j in range(n):
		c = s[j]
		k = s[:j] + s[j + 1:]
		for z in range(n):
			ans = min(ans, k[:z] + c + k[z:])
	print(ans)


def modified_string_BF(test_str):
	clst = list(test_str)
	cmin = [max(clst)] * len(clst)
	for (mx, mch) in enumerate(clst):
		cref = clst.copy()
		cref.pop(mx)
		for np in range(len(clst)):
			ctst = cref.copy()
			ctst.insert(np, mch)
			cmin = min(ctst, cmin)
	return ''.join(cmin)

def modified_string(test_str):
	pc = test_str[0]
	shift = None
	for (cx, ch) in enumerate(test_str):
		if pc > ch:
			if shift is None or ch <= shift:
				if shift is None:
					bsh = pc
					bx = cx - 1
				shift = ch
				sx = cx
		pc = ch
	if shift is not None:
		for (cx, ch) in enumerate(test_str):
			if ch >= shift:
				shup = test_str[:cx] + shift + test_str[cx:sx] + test_str[sx + 1:]
				break
		shbk = test_str[:bx]
		for (nx, nch) in enumerate(test_str[bx + 1:], bx + 1):
			if nch <= bsh:
				shbk += nch
			else:
				shbk += bsh + test_str[nx:]
				break
		else:
			shbk += bsh
		return min(shup, shbk)
	else:
		return test_str
T = int(input())
for tx in range(T):
	N = int(input())
	S = input().strip()
	print(modified_string(S))


for _ in range(int(input())):
	n = int(input())
	mini = ['z'] * 100
	s = list(input().strip())
	ans = min(mini, s)
	t = s[:]
	for i in range(n):
		curr = s[i]
		f = 0
		ind = 0
		temp = s[i]
		for j in range(i):
			if s[j] > curr:
				s.pop(i)
				s.insert(j, temp)
				ans = min(ans, s)
				break
		s = t[:]
	for i in range(n):
		curr = s[i]
		f = 0
		ind = n - 1
		temp = s[i]
		for j in range(i + 1, n):
			if s[j] > curr:
				s.pop(i)
				s.insert(j - 1, temp)
				ans = min(ans, s)
				break
		else:
			s.pop(i)
			s.insert(n - 1, temp)
			ans = min(ans, s)
		s = t[:]
	print(*ans, sep='')


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = s
	for i in range(n):
		new_s = s[:i] + s[i + 1:]
		for j in range(n):
			ans = min(ans, new_s[:j] + s[i] + new_s[j:])
	print(ans)


T = int(input())
for _ in range(T):
	n = int(input())
	s = input().strip()
	answer = s
	for i in range(len(s)):
		c = s[i]
		string = s[:i] + s[i + 1:]
		for j in range(len(string) + 1):
			answer = min(answer, string[:j] + c + string[j:])
	print(answer)


def getInput():
	T = int(input())
	taille = []
	chaine = []
	for i in range(T):
		taille.append(int(input()))
		chaine.append(input())
	return (T, taille, chaine)

def solve(taille, chaine):
	solution = chaine
	for i in range(taille):
		for j in range(taille):
			tempChaine = list(chaine)
			lettre = tempChaine[i]
			tempChaine.pop(i)
			tempChaine.insert(j, lettre)
			if ''.join(tempChaine) < solution:
				solution = ''.join(tempChaine)
	return solution
(T, taille, chaine) = getInput()
for a in range(T):
	print(solve(taille[a], chaine[a]))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = 's'
	for i in range(n):
		chr = s[i]
		str = s[:i] + s[i + 1:]
		for j in range(n):
			ans = min(ans, str[:j] + chr + str[j:])
	print(ans)


t = int(input())
for it in range(t):
	n = int(input())
	s1 = input()
	lowest = s1
	for j in range(n):
		jumper = s1[j]
		s2 = s1[:j] + s1[j + 1:]
		for i in range(n):
			s3 = s2[:i] + jumper + s2[i:]
			if s3 < lowest:
				lowest = s3
	print(lowest)


def Min_str():
	n = int(input())
	s = input()
	temp = s[:]
	for i in range(n):
		s1 = [ord(x) for x in s]
		t = s1[i]
		del s1[i]
		j = 0
		while j < n - 1:
			if s1[j] > t:
				s1[j:j] = [t]
				break
			j += 1
		if len(s1) != n:
			s1 += [t]
		T = ''.join([chr(x) for x in s1])
		if T < temp:
			temp = T
	print(temp)
t = int(input())
for i in range(t):
	Min_str()


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	ans = s
	for i in range(n):
		x = s.copy()
		del x[i]
		for j in range(n):
			ans = min(ans, x[:j] + [s[i]] + x[j:])
	print(''.join(ans))


def rightShift(s, i, j):
	s = list(s)
	while j > i:
		(s[j], s[j - 1]) = (s[j - 1], s[j])
		j -= 1
	return ''.join(s)

def leftShift(s, i, j):
	s = list(s)
	while j > i:
		(s[i], s[i + 1]) = (s[i + 1], s[i])
		i += 1
	return ''.join(s)

def modify(s, deleteAt, insertAt):
	if deleteAt < insertAt:
		s = leftShift(s, deleteAt, insertAt)
	else:
		s = rightShift(s, insertAt, deleteAt)
	return s

def solution():
	N = int(input())
	S = input()
	ans = S
	for i in range(N):
		for j in range(N):
			res = modify(S, i, j)
			ans = min(ans, res)
	print(ans)
T = int(input())
while T > 0:
	T = T - 1
	solution()


def compare(s1, s2, n):
	i = 0
	while i < n:
		if s1[i] < s2[i]:
			return s1
		elif s2[i] < s1[i]:
			return s2
		i += 1
	return s1
for t in range(int(input())):
	n = int(input())
	a = input()
	s = []
	s1 = []
	s2 = []
	temp = []
	for i in range(n):
		s.append(a[i])
		s1.append(a[i])
		s2.append(a[i])
		temp.append([a[i], i])
	temp.sort()
	for i in range(n):
		if s[i] == temp[i][0] or s[i] < temp[i][0]:
			continue
		elif s[i] > temp[i][0]:
			index = temp[i][1]
			j = n - 1
			while j >= 0:
				if s[j] == temp[i][0] and j > index:
					index = j
				j -= 1
			del s1[index]
			s1.insert(i, temp[i][0])
			pos = i + 1
			while pos < n:
				if s2[pos] <= s[i]:
					pos += 1
					continue
				else:
					del s2[i]
					s2.insert(pos - 1, s[i])
					break
			if pos >= n:
				del s2[i]
				s2.insert(n - 1, s[i])
			break
	x = ''.join(s1)
	y = ''.join(s2)
	ans = compare(x, y, n)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	wow = s
	for i in range(n):
		now = s[:i] + s[i + 1:]
		for j in range(n):
			wow = min(wow, now[:j] + s[i] + now[j:])
	print(wow)


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	ans = s
	(val, val1) = ('', '')
	for i in range(n):
		val = s[:i] + s[i + 1:]
		for j in range(n):
			val1 = val[:j] + s[i] + val[j:]
			ans = min(ans, val1)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	l = []
	for i in range(n):
		yo = s[:i] + s[i + 1:]
		for j in range(n):
			k1 = yo[:j] + s[i] + yo[j:]
			l.append(k1)
	l.sort()
	print(l[0])


def modified_string(test_str):
	clst = list(test_str)
	cmin = [max(clst)] * len(clst)
	for (mx, mch) in enumerate(clst):
		cref = clst.copy()
		cref.pop(mx)
		for np in range(len(clst)):
			ctst = cref.copy()
			ctst.insert(np, mch)
			cmin = min(ctst, cmin)
	return ''.join(cmin)
T = int(input())
for tx in range(T):
	N = int(input())
	S = input().strip()
	print(modified_string(S))


def modify(s, i, j):
	k = s[i]
	del s[i]
	s.insert(j, k)
	return str(s)
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	ans = str(s)
	for i in range(n):
		for j in range(n):
			if i != j:
				ans = min(ans, modify(s, i, j))
			k = s[j]
			del s[j]
			s.insert(i, k)
	for i in ans:
		if ord(i) >= 65 and ord(i) <= 90:
			print(i, end='')
	print()


import sys

def modify(s, i, j):
	c = s[i]
	t = s[:i] + s[i + 1:]
	ret = t[:j] + c + t[j:]
	return ret
t = int(sys.stdin.readline())
while t > 0:
	t -= 1
	n = int(sys.stdin.readline())
	s = sys.stdin.readline().strip()
	m = s
	for i in range(n):
		for j in range(n):
			if i != j:
				m = min(m, modify(s, i, j))
	print(m)