Increasing Decreasing String - Problem
You are given a string s. Reorder the string using the following algorithm:
- Remove the smallest character from
sand append it to the result. - Remove the smallest character from
sthat 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
sand append it to the result. - Remove the largest character from
sthat 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
shave 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code