Given a string s, return the result string after applying the following algorithm:
-
Pick the
smallest
character from
s
and append it to the result.
-
Pick the
smallest
character from
s
that is greater than the last appended character and append it.
-
Repeat step 2 until you cannot pick more characters.
-
Pick the
largest
character from
s
and append it to the result.
-
Pick the
largest
character from
s
that is smaller than the last appended character and append it.
-
Repeat step 5 until you cannot pick more characters.
-
Repeat steps 1 to 6 until you have picked all characters from
s
.
In each step, if the smallest or the largest character appears more than once, you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm.
Function Signature
def sort_string(s: str) -> str:
Rules
-
Each character of
s
is picked exactly once, so "from
s
" means from the characters not picked yet. The result is a rearrangement of
s
.
-
Steps 1 and 4 do not compare against the last appended character. Only steps 2 and 5 do.
-
Copies of the same letter are identical, so choosing any occurrence gives the same string and the expected output is unique.
Constraints
-
1 <= s.length <= 500
-
s
consists of only lowercase English letters.
Examples
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
The counts are a:4, b:4, c:4. Each round appends the ascending pass "abc" and then the descending pass "cba", and two rounds place all 12 characters.
Input: s = "rat"
Output: "art"
The ascending pass picks a, r and t, which uses every character, so the descending pass has nothing left to add.
Input: s = "banana"
Output: "abnnaa"
The first ascending pass takes "abn", leaving a, a, n. The descending pass takes "na", leaving one a, which the next ascending pass appends.