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 INPUT String s: "aaaabbbbcccc" Character Frequency: a a a a x4 b b b b x4 c c c c x4 Count array: [4, 4, 4] for chars a, b, c ALGORITHM STEPS 1 Count Characters Build frequency array [26] 2 Ascending Phase Pick a-->b-->c (smallest up) 3 Descending Phase Pick c-->b-->a (largest down) 4 Repeat Until Empty Loop until all chars used Iteration Progress: Round 1: a-->b-->c-->c-->b-->a = "abccba" Round 2: a-->b-->c-->c-->b-->a = "abccba" Counts: [0, 0, 0] - Done! FINAL RESULT Reordered String: "abccbaabccba" Pattern Visualization: a b c c b a a b c c b a OK - Length: 12 chars Key Insight: Use a count array of size 26 to track character frequencies. In each iteration, traverse a-->z (ascending) then z-->a (descending), appending available characters. This creates the "wave" pattern efficiently in O(n) time where n is the string length. TutorialsPoint - Increasing Decreasing String | Optimal Solution
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