Take the string of brackets ]][][[
. When you rotate it to the right once, you get []][][
. If you rotate it again, you get [[]][]
. All brackets in this string are balanced.
The Task:
Your program (or function) will be given a string of brackets, represented in any reasonable format (including using other things in place of the brackets, like -1
and 1
). The numbers of opening and closing brackets will always be equal, so [
or ][]
won't be given as inputs.
Output should be a rotation of those brackets which is balanced. You can check this by repeatedly removing pairs of brackets ([]
). With a balanced string of brackets, none will be left over.
Rotating a string to the right involves taking the last character, and moving it to the beginning. For example, 01234567
rotated right 3 times would be 56701234
. The direction of rotation doesn't matter, but no brackets should be added, discarded, mirrored, etc. If multiple solutions are possible, such as [][[]]
or [[]][]
, you can return any of them.
Test Cases:
[] -> []
]][[ -> [[]]
[][]][ -> [[][]]
][][[] -> [[]][] OR [][[]]
[[[][][]]] -> [[[][][]]]
]]][][][[[ -> [[[]]][][] OR [][[[]]][] OR [][][[[]]]
Other:
This is code-golf, so shortest answer in bytes per language wins!
.
. The example input would become]].[[
. You'll always end up with/]*[*/
, with some dots interwoven occasionally. You can always then rotate that to be/[*]*/
, which is balanced. \$\endgroup\$[
with +1 and]
with -1. Consider instead of a string as a ring of these integers. Choose an arbitrary point and starting with zero pass around the ring adding each integer to the sum. (this will return to zero). If the sum never goes below 0 you are fine, if it does choose the minimum point and start from there instead. Now it will never go below zero, so that is where you begin / end the string. \$\endgroup\$