Swap and Reverse (Codeforces 1864B)
Tags: Greedy, strings

You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters, and an integer $$$k$$$. In one step you can perform any one of the two operations below:  Pick an index $$$i$$$ ($$$1 \le i \le n - 2$$$) and swap $$$s_{i}$$$ and $$$s_{i+2}$$$.  Pick an index $$$i$$$ ($$$1 \le i \le n-k+1$$$) and reverse the order of letters formed by the range $$$[i,i+k-1]$$$ of the string. Formally, if the string currently is equal to $$$s_1\ldots s_{i-1}s_is_{i+1}\ldots s_{i+k-2}s_{i+k-1}s_{i+k}\ldots s_{n-1}s_n$$$, change it to $$$s_1\ldots s_{i-1}s_{i+k-1}s_{i+k-2}\ldots s_{i+1}s_is_{i+k}\ldots s_{n-1}s_n$$$. You can make as many steps as you want (possibly, zero). Your task is to find the lexicographically smallest string you can obtain after some number of steps. A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. 

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows.The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 10^5$$$).The second line of each test case contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output: For each test case, print the lexicographically smallest string after doing some (possibly, zero) steps.

Note: In the first test case, we can obtain the string "aimn" using the following operations:  Reverse the range $$$[3,4]$$$. The string turns into "niam".  Swap $$$s_1$$$ and $$$s_3$$$. The string turns into "ainm".  Reverse the range $$$[3,4]$$$. The string turns into "aimn". It can be proven that we cannot obtain any string lexicographically smaller than "aimn". Therefore, "aimn" is the answer.In the second test case, we can obtain the string "aandp" using the following operations:  Swap $$$s_3$$$ and $$$s_5$$$. The string turns into "paadn".  Swap $$$s_1$$$ and $$$s_3$$$. The string turns into "aapdn".  Swap $$$s_3$$$ and $$$s_5$$$. The string turns into "aandp". It can be proven that we cannot obtain any string lexicographically smaller than "aandp". Therefore, "aandp" is the answer.

Sample Inputs:
5
4 2
nima
5 3
panda
9 2
theforces
7 3
amirfar
6 4
rounds

Sample Outputs:
aimn
aandp
ceefhorst
aafmirr
dnorsu

Solution (Python):
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ni():
    return int(input())

def si():
    return input()

def mi():
    return map(int, input().strip().split())

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

def kshift(i, ind, k, l):
    while ind != i:
        l[ind - (k - 1):ind + 1] = l[ind + 1 - 1:ind - (k - 1) - 1:-1]
        ind -= k - 1
    return l

def shift(i, ind, l):
    while ind != i:
        (l[ind], l[ind - 2]) = (l[ind - 2], l[ind])
        ind -= 2
    return l

def main():
    for _ in range(ni()):
        (n, k) = mi()
        s = si()
        l = [*s]
        if k % 2 == 0:
            print(''.join(sorted(l)))
            continue
        else:
            ss = ''
            se = ''.join(sorted(s[::2]))
            so = ''.join(sorted(s[1::2]))
            i = 0
            while i < len(se):
                if i < len(so):
                    ss += se[i]
                    ss += so[i]
                    i += 1
                    continue
                ss += se[i]
                i += 1
            print(ss.strip())
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._file = 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')
if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline

def get(s, n, k, i=0):
    S = ''.join(sorted(s))
    if s == S:
        return S
    if k % 2 == 1:
        (s1, s2) = (sorted(s[::2]), sorted(s[1::2]))
        return ''.join((s2[i // 2] if i % 2 else s1[i // 2] for i in range(n)))
    if k % 2 == 0:
        return S
T = int(input())
while T:
    T -= 1
    (N, K) = map(int, input().split())
    S = input().strip()
    print(get(S, N, K))

Solution (Python):
from sys import stdin, setrecursionlimit
input = stdin.readline
for _ in range(int(input())):
    (n, k) = map(int, input().split())
    s = input().strip()
    if k % 2 == 0:
        print(''.join(sorted(s)))
    else:
        even = sorted(s[::2])
        odd = sorted(s[1::2])
        s = []
        for i in range(len(odd)):
            s.append(even[i])
            s.append(odd[i])
        if len(even) > len(odd):
            s.append(even[-1])
        print(''.join(s))