Increasing Decreasing String

You are given a string s. Reorder the string using the following algorithm:

  • Remove the smallest character from s and append it to the result.
  • Remove the smallest character from s that is greater than the last appended character, and append it to the result.
  • Repeat step 2 until no more characters can be removed.
  • Remove the largest character from s and append it to the result.
  • Remove the largest character from s that is smaller than the last appended character, and append it to the result.
  • Repeat step 5 until no more characters can be removed.
  • Repeat steps 1 through 6 until all characters from s have been removed.

If the smallest or largest character appears more than once, you may choose any occurrence to append to the result.

Return the resulting string after reordering s using this algorithm.

Example 1
Inputs = "aaaabbbbcccc"
Output"abccbaabccba"
After the first increasing and decreasing pass, the result is abccba; repeating the process with the remaining characters produces abccbaabccba.
Example 2
Inputs = "rat"
Output"art"
The word rat becomes art after re-ordering it with the mentioned algorithm.

Constraints

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate