Problem:
Score : 1300 points

Problem Statement

Takahashi has a string S of length N consisting of lowercase English letters.
On this string, he will perform the following operation K times:

Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order.

Let S' be some contiguous substring of U with length N, and replace S with S'.

Among the strings that can be the string S after the K operations, find the lexicographically smallest possible one.

Constraints

1 \leq N \leq 5000

1 \leq K \leq 10^9

|S|=N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the lexicographically smallest possible string that can be the string S after the K operations.

Sample Input 1

5 1
bacba

Sample Output 1

aabca

When S=bacba, T=abcab, U=bacbaabcab, and the optimal choice of S' is S'=aabca.

Sample Input 2

10 2
bbaabbbaab

Sample Output 2

aaaabbaabb

Solution in Java8 (OpenJDK 1.8.0) (judge verdict: Wrong Answer)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
    	try {
    		final int N = sc.nextInt();
    		int K = sc.nextInt();
    		StringBuilder S = new StringBuilder(sc.next());
    		boolean firstTime = true;
    		int step = 1;

    		while (K > 0) {
    			StringBuilder T = new StringBuilder(S.toString());
    			T.reverse();
    			StringBuilder revU = new StringBuilder(S.toString() + T.toString());
    			revU.reverse();
    			String sDash = S.toString();
    			for (int i=N; i>=0; i-=step) {
    				String tmp = revU.substring(i, i+N);
    				// if (sDash.compareTo(tmp) > 0) {
    				if (compareTo(sDash, tmp, step) > 0) {
    					sDash = tmp;
    				} else {
    					if (!firstTime) {
        					break;
    					}
    				}
    			}
				if (firstTime) {
					firstTime = false;
					/*
					if (Math.pow(2, K) > N) {
						char c = sDash.charAt(0);
						for (int i=0; i<N; i++) {
							System.out.print(c);
						}
						System.out.println();
						System.exit(0);
					}
					*/
				} else {
					if (step < 4096) {
						step += step;
					}
				}

    			K--;
    			S = new StringBuilder(sDash);
    			S.reverse();
    		}
    		System.out.println(S.reverse());

    	} finally {
    		sc.close();
    	}
    }

    public static int compareTo(String value, String anotherString, int step) {
        int len1 = value.length();
        int len2 = anotherString.length();
        int lim = Math.min(len1, len2);
        char v1[] = value.toCharArray();
        char v2[] = anotherString.toCharArray();

        int k = 0;
        while (k < lim) {
        	// System.out.print(lim + " / ");
        	// System.out.println(k);
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k+=step;
        }
        return len1 - len2;
    }
}