FunctionRacerProblemsRace

Swap the Balanced Pieces

HardRecursionPython, JavaScript, TypeScript, Java, C++

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

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems