Under construction

Still being built. Things may change

String Construction

Interview

Time limit1sMemory limit128 MB

Summary
Repeatedly take the leftmost or rightmost character of S and append it to T; among all such T, output the lexicographically smallest, wrapping lines at 80 characters.
Level

Medium5 of 10

Topics
Greedy, String, Two pointers, Implementation
Solved
No attempts yet

Problem

A string SS of length NN is given.

Using the characters of SS, build a new string TT. Initially TT is empty. Repeat one of the following two operations until SS becomes empty:

  • Remove the first (leftmost) character of SS and append it to the end of TT.
  • Remove the last (rightmost) character of SS and append it to the end of TT.

Among all strings TT that can be produced this way, write a program that finds the lexicographically smallest one.

Input

The first line contains the length NN of the string SS. (1≤N≤2 0001 \le N \le 2\,000)

Each of the next NN lines contains one character of SS, given in order.

Output

Print the lexicographically smallest string TT that can be produced. Insert a line break after every 80 characters.

Hint

Starting from S=S = ACDBCB, one way to build TT proceeds as follows:

StepRemaining SSTT
1ACDBCB(empty)
2CDBCBA
3CDBCAB
4CDBABC
5CDABCB
6DABCBC
7(empty)ABCBCD

Examples1

  1. Example 1

    Input
    6
    A
    C
    D
    B
    C
    B
    
    Expected output
    ABCBCD