Increasing Decreasing String - Problem

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

  1. Remove the smallest character from s and append it to the result.
  2. Remove the smallest character from s that is greater than the last appended character, and append it to the result.
  3. Repeat step 2 until no more characters can be removed.
  4. Remove the largest character from s and append it to the result.
  5. Remove the largest character from s that is smaller than the last appended character, and append it to the result.
  6. Repeat step 5 until no more characters can be removed.
  7. 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.

Input & Output

Example 1 — Basic Case
$ Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
💡 Note: First cycle: ascending a→b→c, descending c→b→a. Second cycle: ascending a→b→c, descending c→b→a. Result: abccbaabccba
Example 2 — Single Character
$ Input: s = "rat"
Output: "art"
💡 Note: Ascending phase picks 'a', then 'r', then 't'. No characters left for descending phase. Result: art
Example 3 — Repeated Pattern
$ Input: s = "leetcode"
Output: "cdelotee"
💡 Note: First ascending: c→d→e→l→o→t. Then descending: e→e. All characters used. Result: cdelotee

Constraints

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

Visualization

Tap to expand
Increasing Decreasing String AlgorithmInput: aaaabbbbccccAscendingDescendingRepeata → b → cc → b → aUntil doneOutput: abccbaabccbaPattern: abc|cba|abc|cba (two complete cycles)
Understanding the Visualization
1
Input
String 'aaaabbbbcccc' with character frequencies
2
Process
Alternate ascending (a→b→c) and descending (c→b→a) selections
3
Output
Final string 'abccbaabccba' following the pattern
Key Takeaway
🎯 Key Insight: Use frequency counting to avoid string manipulation and systematically alternate between ascending and descending character selection
Asked in
Amazon 15 Google 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen