Swap the Balanced Pieces
s is a balanced string of round brackets. A piece of s is balanced when it is not empty and its brackets match up among themselves, like () or (()()).
One move takes two balanced pieces that stand directly next to each other and swaps them. Make as many moves as you like.
Return the string you can reach that comes first in alphabetical order, where ( comes before ).
Example 1
s "()(())"
returns "(())()"
Swap () with (()). The longer run of ( now comes first.
Example 2
s "(()(()))"
returns "((())())"
The same swap, one level down inside the outer pair.
Example 3
s "()()"
returns "()()"
The two pieces are equal, so no move changes anything.
Constraints
2 <= len(s) <= 60sis made of(and)and is balanced
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Times Before PlusHard
- Valleys in the Folded StripHard
- Count the BoxesBeginner
- Digit TallyBeginner
- Equal NeighboursBeginner
- Halving TotalBeginner
- Largest DigitBeginner
- Multiply It OutBeginner