[Question]
  [
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](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins!
  
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 5 bytes
```
·πô¬πŒ∑‚óÑ‚à´
```
[Try it online!](https://tio.run/##yygtzv6vkPuoqfHQNi6FXA1FpehYpUN7H7VN0nzU1JSr8ahtgoutevT/hztnHtp5bvuj6S2POlb///8/OpYrNjY6mis6NhpIcwHJaKBQdDSIDxQByYJZQBEkJgA "Husk ‚Äì Try It Online")
No loops, no recursion, just a straightforward simple operation. Encodes `[` as `1` and `]` as `-1`.
```
·πô¬πŒ∑‚óÑ‚à´
·πô¬π       Rotate the list left by
  Œ∑        the (1-based) index
   ‚óÑ         of the minimum
    ‚à´      in the list of cumulative sums
 
```
This comes from observing that the list of cumulative sums will have a minimum at the point where the most closed brackets are preceding open brackets. By moving all the previous brackets to the end, we can guarantee that there won't be any prefix containing more closed than open brackets.
---
## Previous answer, 7 bytes
```
Œ©»Ø¬¨‚ñº‚à´·πô1
```
[Try it online!](https://tio.run/##yygtzv6fq6GoFB2rdGjvo7ZJmo@aGnM1HrVNcLFVj/5/buWJ9YfWPJq251HH6oc7Zxr@//9fKTY2NhoEo6OVAA "Husk ‚Äì Try It Online")
Encodes `[` as `1` and `]` as `-1`, following [HyperNeutrino's idea](https://codegolf.stackexchange.com/a/221295/62393) to use the cumulative sum, but then uses an additional observation:
Since we are working with an equal number of open and closed brackets, the total sum will always be `0`. If at any point the string is unbalanced, the cumulative sum at that point will be negative. From this, we can say that a string will be balanced if the minimum of its cumulative sum is exactly `0`.
```
Œ©(¬¨‚ñº‚à´)·πô1
      ·πô1    Rotate by 1
Œ©           until
   ‚ñº         the minimum
    ‚à´        of the cumulative sums
  ¬¨          is 0
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~42~~ 34 bytes
```
{({S/.//~$/}...{try !.EVAL}).tail}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1qjOlhfT1@/TkW/Vk9Pr7qkqFJBUc81zNGnVlOvJDEzp/Z/cWKlQppCXa5@TLCWvkJafpFCTmZeavH/6FgFONC1U1CIjuWKjY2ORhGKjo3lio4FktEogiBhIBENMwKmFsj3D1IASwD1gRUCWbEwBTA@0B4wKxpkG0wKIgTTD@FDeVA@AA "Perl 6 ‚Äì Try It Online")
In Raku, a set of balanced square brackets is entirely valid syntax, so we can simply rotate the string until it `EVAL`s successfully, and take the last element.
### Explanation
```
{                                }  # Anonymous codeblock taking a string
  {S/.//   }                        # Remove the first character
        ~$/                         # And add it to the end
 (          ...            )        # Repeat until
               {try !.EVAL}            # The program can be eval'd
                                       # This returns ![] (true) if successful
                            .tail   # Return the last element
```
I thought [this 31 byte program](https://tio.run/##K0gtyjH7/79YX0NPS1NDT1NfxVDFQL80ryQzR6GkqFJBUc81zNHn///oWK7Y2OhorujYaCDNBSSjgULR0SA@UAQkC2YBRf7lF5Rk5ucV/9ctAAA) using the `-p` flag would work, but either TIO is too outdated or Raku has some sort of weird behaviour about `until`/`while` and `$_`. Until I can test it using the latest version, you can check it [like so](https://tio.run/##K0gtyjH7n5ZfpKCRk5mXWqypoGunoJKoUM2lEq9gC2RZ/y/W19DT0tTQ09RXMVQx0C/NK8nMUSgpqlRQ1HMNc/T5b81VnFipoBLPVfs/OpYrNjY6mis6NhpIcwHJaKBQdDSIDxQByYJZQBEA).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
√ÑM·πô@
```
[Try it online!](https://tio.run/##y0rNyan8//9wi@/DnTMd/ts@apgb@3DHkkcNMw@3P2qY4fFwd/ejxn2x0ZH//yvFxsZGg2B0tBIA "Jelly ‚Äì Try It Online")
Similar approach to [Leo's answer](https://codegolf.stackexchange.com/a/221300/66833), give that an upvote!
Uses `-1` and `1` for `[` and `]` and returns all valid rotations
By swapping the signs from Leo's approach, we can operate on the maximal elements, rather than minimal, as Jelly has a builtin `M` to return the indices of maximal elements, thus saving a byte
## How it works
```
√ÑM·πô@ - Main link. Takes a list of 1 and -1, A
√Ñ    - Take the cumulative sums
 M   - Yield the indices of the maximal elements
  ·πô@ - Rotate A that many times for each index
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~74~~ ~~72~~ 69 bytes
```
def f(s):
 try:exec s.replace(')','),');print s
 except:f(s[1:]+s[0])
```
[Try it online!](https://tio.run/##PYtBCoMwEEX3OcXgJn@olOoyPYq4kHRCC2JDkoWePo61LQzMvP/nxa0830tf60MCBWR2hkranKziKV@TxHnyAsu2taxzj@m1FMqGZPUSi1Nn6Nx4ycNt5BrQgBs2upmB8wJD4Zsq/D6Ao9Hub3wQh1d3 "Python 2 ‚Äì Try It Online")
Tried a similar approach to *Jo King*'s Raku answer by evaluating the bracket string, only difference being an added `,` after every `)` so that the expression is valid.
Takes `(` and `)` instead of `[` and `]`.
*-2 bytes thanks to Sisyphus, -3 bytes thanks to dingledooper*
[51 bytes if it's allowed to take ( and ), instead of ( and ) üëÄ](https://tio.run/##TYwxDoAgEAR7XnGx2osUaolPMVZ6RBslQKGvR9Bo7HZn586dcdm3LqVZLFkENoqiP40cMlHonV@3SEGRHJO4aLIxtGasw9CMnCwqsK5Y5cCaNfDkDHH3dyrgM4Fnv5X/@UtR/qQL)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
[This algorithm.](https://codegolf.stackexchange.com/a/221304/43319)
Anonymous prefix lambda, taking `-1` for `[` and `1` for `]`.
```
{‚çµ‚åΩ‚ç®‚äÉ‚çí+\‚çµ}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHPXsf9a541NX8qHeSdgxQoPZ/2qO2CY96@4Bih9YbP2qb@KhvanCQM5AM8fAM/l9QlAqUP7TeUEs9Wt32UdciroL84hKgULV6tEKserSRNtCQ2FqwqEKaAlC5gnp0rDoKPzY2OlodTUU0UBBNFVAQXWd0NEglUC2GiWDhaJC5XJr5aWlcXNGxCnCga6egEB3LBbIXRQhoEBfEahRBkDDEdlS1QL5/kAJYAqgP7hSYAhifC@EahBRECKYfwofyoHwA "APL (Dyalog Unicode) ‚Äì Try It Online") ([This template](https://codegolf.stackexchange.com/a/221298/43319))
`{`‚Ä¶`}` "dfn"; argument is `‚çµ`:
‚ÄÉ`+\‚çµ`‚ÄÉcumulative sum of the argument
‚ÄÉ`‚çí`‚ÄÉindices that would sort that descending (i.e. index of the largest, index of the next-largest, etc.)
‚ÄÉ`‚äÉ`‚ÄÉthe first of that (i.e. the index of the largest)
‚ÄÉ`‚çµ‚åΩ‚ç®`‚ÄÉuse that to rotate the argument to the left
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
until(all(>0).scanl(+)1)$drop<>take$1
```
[Try it online!](https://tio.run/##bY7NDoIwEITvPMUeOLSREnsHTl55AuSw4Ucbl7ah6@tbhQQlarLJ7peZzcwVw20gimbybmY4IWNeO@tMD0IUlZTJWJ7j3bIhgUSiOso8dGhJHKSWaT87X1SMtyHVkYfAAUpoGp2B0m0GjVqvDJZZ@INvZbPtnNv3Dr@X@olQ/6xrQJskExr7ajahr8HPxjKkC8AIa@n46EbCS4iq8/4J "Haskell ‚Äì Try It Online")
*Saved 2 bytes using `<>`.*
Takes in a list of 1's and -1's. Actually pretty readable:
```
until            until
 (all(>0).       we get all positive values from
  scanl(+)1)     the cumulative sums of the list starting from 1,
 $drop<>take     rotate the list
 $1              by 1
```
The `drop<>take` rotates by using `<>` to concatenate the list with elements `drop`ped from the start and the list with that many elements `take`n from the start. The `(<>)` is imported in the TIO link but is available in base starting with 8.4.1; [see this tip](https://codegolf.stackexchange.com/a/177774/20260). We could also do `tail<>take 1` for the same length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
·πôJ√Ñ-e∆ä√ê·∏ü
```
[Try it online!](https://tio.run/##y0rNyan8///hzpleh1t0U491HZ7wcMf8/7aPGuZGP9yx5FHDzMPtjxpmeDzc3f2ocV90bOT//0qxsbHRIBgdrQQA "Jelly ‚Äì Try It Online")
-2 bytes thanks to ChartZ Belatedly + 1 byte saved from being allowed to return all valid configurations instead of just one
## Explanation
```
·πôJ√Ñ-e∆ä√ê·∏ü  Main Link
·πô         Rotate by
 J        [1, 2, ..., len(input)]
      √ê·∏ü  Filter: keep all elements where the following is falsy (in this case, a list of all zeroes):
  √Ñ       Cumulative Sum
    e     equal to (vectorize)
   -      -1
```
Basically, keep all arrangements where the cumulative sum is never equal to -1 (clever observation from ChartZ that since the cumsum changes by 1 each time and starts at 0, if any value is negative, then there must be a -1 somewhere, so rather than doing `<0$` we can do `-e`. and then also that the filter quick accepts a list of zeroes as falsy so I don't have to use the `any` atom)
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 57 bytes
```
f=lambda s,t=1:s*all((t:=t+n)for n in s)or f(s[1:]+s[:1])
```
[Try it online!](https://tio.run/##bYzBCsMgEETv/Yo9ro0ell6K4JeIB0sjEawRtS39emtDaEPosrDz2JlJrzrN8XROuTWngr1drhYKr4pkOdoQEKtUdYjMzRki@AiFdeWwaJJmKFqSYe05@TACyZR9rOhwfNiAPqZ7RdanaeIgyBy0WASHz3b80fexmja@Nbqh/RH7evHPubS/AQ "Python 3.8 (pre-release) ‚Äì Try It Online")
Takes in a list of 1's and -1's.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
(‚ä¢‚åΩ‚ç®1‚àä+\)‚ç£‚â°
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR16JHPXsf9a4wfNTRpR2j@ah38aPOhf/THrVNeNTb96ir@dB640dtEx/1TQ0OcgaSIR6ewf8LilKB8ofWG2qpR6vbAo3gKsgvLgEKVatHK8SqRxtpP@rdGlsLFlVIUwAqV1CPjlVH4cfGRkero6mIBgqiqQIKouuMjgapBKrFMBEsHA0yl0szPy2Niys6VgEOdO0UFKJjuUD2oggBDeKCWI0iCBKG2I6qFsj3D1IASwD1wZ0CUwDjcyFcg5CCCMH0Q/hQHpQPAA "APL (Dyalog Unicode) ‚Äì Try It Online")
An APL port of [Jonah's golfed answer](https://codegolf.stackexchange.com/a/221296/78410), which in turn uses [Leo's observation](https://codegolf.stackexchange.com/questions/221293/rotate-brackets-until-theyre-balanced#comment514707_221295). Like Jonah's, the input is `-1` for `[` and `1` for `]`.
### How it works
```
(‚ä¢‚åΩ‚ç®1‚àä+\)‚ç£‚â°  ‚çù Input: a vector of -1s and 1s, -1 for open and 1 for close
(...)‚ç£‚â°  ‚çù Repeat until it does not change...
1‚àä+\     ‚çù   1 if cumulative sum has a 1, 0 otherwise
‚ä¢‚åΩ‚ç®      ‚çù   Rotate left ^ times (so it stops when the above result is zero)
```
[Answer]
# Scratch 3.0, 49 blocks/407 bytes
[![pain](https://i.stack.imgur.com/kGumm.png)](https://i.stack.imgur.com/kGumm.png)
As SB Syntax:
```
define C
set[T v]to(0
set[i v]to(1
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1
define(s
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v]
set[i v]to((i)+(1
end
C
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v]
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C
end
say(S
```
Because rotating a string in Scratch/bracket matching is a really good idea. Use `a` for opening brackets and `b` for closing brackets.
## Explained
```
define C -- Helper function used for checking if the brackets are balanced
set[T v]to(0   
set[i v]to(1 --- T = running tally, i = string index, Y = return value
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else                 ---- Opening brackets (a) increment the tally by 1. Closing brackets (b) decrement the tally by 1. If the brackets are balanced, this tally will never go below 0, as the brackets will cancel each other out
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1
define(s --- Main function
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v] --- Place every character of the input into a list
set[i v]to((i)+(1
end
C ---- Check if the inital input is balanced
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v]  --- Rotate the string once
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C   ---------- And check each rotation
end
say(S
```
[Answer]
# [J](http://jsoftware.com/), 40 29 19 18 15 14 13 bytes
```
|.~1+0{&\:+/\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/a/TqDLUNqtVirLT1Y/5rcpWkFpfY6imkJmfkO2joWqVpqmnEG2qrRyvEqmfqxWpycXGpR8eqK4CUKYBYQG50LFwgNjY6GiKEJAjmgIVjUdSCuWDVIBVAGYQOhAhYVyxIANmWWKig@n8A "J ‚Äì Try It Online")
-11 after applying HyperNeutrino's scan sum idea
-10 after reading Leo's comment to HyperNeutrino: `while(any of the cumulative sum is negative)(rotate by 1)`
-3 thanks to a clever observation by Bubbler
Takes input as a list of integers, where `[ = _1` and `] = 1` -- reversing the more natural order saves 1 byte.
## how
* `|.~` Rotate by...
* `1+` 1 plus...
* `0{` the first element of...
* `\:` the grade down of...
* `+/\` the scan sum.
That is, take the index of the max element of the scan sum, add one to it, and rotate by that amount.
[Answer]
# [Perl 5](https://www.perl.org/), 30 bytes
```
$_=chop.$_ while s/<(?R)*>//gr
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jY5I79ATyVeoTwjMydVoVjfRsM@SFPLTl8/vej/fxs7Ljs7GxsuGzsbIM0FJG2AQjY2ID5QBCQLZgFF/uUXlGTm5xX/1y3IAQA "Perl 5 ‚Äì Try It Online")
Uses `<>` as the bracket delimiters.
The regex `s/<(?R)*>//gr` recursively substitutes bracket patterns with the empty string, and instead of mutating the string returns the final value. If this is empty, then all our brackets are fully matched and since the empty string is falsy, the loop stops. Else we rotate the string one using the construction `$_=chop.$_`.
-1 thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) by replacing the ugly `s/.//,$_.=$&` with the much more elegant `$_=chop.$_`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
f=a=>([c,...r]=a).some(v=>(c+=v)>=0)?f([...r,a[0]]):a
```
[Try it online!](https://tio.run/##dY0xDoMwDEX3nsJbYrVEsFIZDmJ5iFKoQEAQQVw/DbAhunh473//3m42uKWb12zynybGlixVmt3LGLMIWTTBj43eEnRP2rCiHOtW865flnMRLG1cKVB10iBmtLN2QBWkQwSKFdSQFVBCgXi1iddHpAQlCk3vu0krhQ/np@CHxgz@q1etOEl8X6kI8x1n4aRuG0nd/2LeW6n3Z@mQfO7FHw "JavaScript (Node.js) ‚Äì Try It Online")
Input array of \$\pm 1\$, output rotated array.
Thanks [user81655](https://codegolf.stackexchange.com/users/46855/user81655) for -1 byte.
[Answer]
# Javascript, 52 bytes
(Sorry if i formatted my answer wrong, i'm brand new here.)
## Golf version
```
a=>{while(t=0,a.some(v=>(t+=v)<0))a.push(a.shift())}
```
## More readable version (and you can try it out)
```
function rotateArrayUntilBalanced(array) {
  var total; // Create a total variable
  while (total=0,array.some(value => (total += value) < 0)) { // This tests if the array is still unbalanced
    array.push(array.shift()); // Shift array right
  }
}
button.onclick = function () {
  const array = input.value.split('').map(value => (value == '[' ? 1 : -1));
  rotateArrayUntilBalanced(array);
  resultArea.innerText = array.map(value => (value == 1 ? '[' : ']')).join('');
}
```
```
<input id="input" placeholder="brackets go here">
<button id="button">Go</button>
<div id="resultArea"></div>
```
[Answer]
# [R](https://www.r-project.org/), 80 bytes
```
function(x){while(min(cumsum(92-(y=utf8ToInt(x)))))x=intToUtf8(c(y[-1],y[1]));x}
```
[Try it online!](https://tio.run/##bY@9CsIwFIV3nyLokoAd6qRI3Z0EqdPlIjW0GLQJtAm2iM9eY5pI0dztnPPdv2ZolC50eb40Bb@Vus2GykiuhZK0Y8/HVdxLWgtJualbU9PNKqF9ZnS1ztVeast8qsuE1Lk6WZty2kOS4rKHFBnbdq/fDXQOOGdkQb6V7AgBnP1xiABT0nGAERLQ2hPWk1HWujC9IEwFJIcjcWFsgxtnI985dgUvdruLIHwQ@NEOm0btldfDGw "R ‚Äì Try It Online")
Input is string of square-brackets.  
Alternatively, a port of [Leo's Husk answer](https://codegolf.stackexchange.com/a/221300/95126) using a vector of `1`s & `-1`s as input is only [48 bytes](https://tio.run/##rZFPS8QwEMXvfophFyTBrbCedKF79yTIegqhxJiyQZpZk4nWT1/Tv1qht@aUmeT93pvENx5JkSlevdLvhkLelNFpsuhYzTWrdzUXwXwwldf85uts9fm2so7pWIVYpStcNlvQ6D6NJyCEayg9VmBU@M4IM2/UG4xssC5Q28AS9rtsD6ptXSIdrgZCQVigM0WyiCFt8j9hHu6ySOX9CR8dpXKStH6LIuvohC9JxpI8iZZV7N9DsIVIbCPkhnMOW5hWdgQQcg22lELM6R1bSLlO8gSa8Qf6SvzEEfPXGdMLCU/P0B2vM0kXOsEmt95p7K7zFx1M/P7I6NEfjBP19VANdfMD).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
a=>eval("try{Function(a.replace(/]/g,'-1]'));a}catch{f(a.slice(1)+a[0])}")
```
[Try it online!](https://tio.run/##dY1BDoMgFET3PYYbIK1a1waXXuKHxQ9FS0PAADVpjGen1O4aup03b@aBKwbp9RJr624qTTwhH9SKhlbRv7bxaWXUzlJsvFoMSkVb0c4XUneCMNbjLjHK@zblQjA6446dEa6C7RVLkQc@TDSw/iSdDc6oxriZRkrgsH9TIQBKOQjIqGhkVN4C@FjZ@/N0QPj@pTc "JavaScript (Node.js) ‚Äì Try It Online")
Convert each `]` to `-1]`, and try to check if there are any syntax error...
This is ES2019.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~74~~ 72 bytes
```
f=lambda a:min(sum(a[:i])for i in range(len(a)))<0and f([a.pop()]+a)or a
```
[Try it online!](https://tio.run/##XYrBCsIwEETvfsUedzGVBm9Fv6TkMKWNBppNiPXg18e0Bw/CMAPvTf5sz6TXWv19RZxmEIYYlF/vyBiH4MSnQoGCUoE@Fl4XZYjIrYfO5HnEJafM4s6Q9kTNJejGTVhDnXUipx/pDmRoz7@w5qh9mqpf "Python 3 ‚Äì Try It Online")
Takes input as a list of 1s and -1s, with 1 denoting `[` and -1 denoting `]`.
For a valid bracket sequence, no prefix of the array will have a sum less than 0, so if the current array is not a valid bracket sequence, rotate it by 1 and try again.
*-2 bytes thanks to tsh*
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
lambda a:min((sum(a[:i]),a[i:]+a[:i])for i in range(len(a)))[1]
```
[Try it online!](https://tio.run/##XYzBDoIwEETvfsXeuo1oQrw16Zese1gj6BooBOrBr68FjAGO82bm9Z/47MIl1f6aGmlvdwFxrQbE8d2ikFO2hZA6Pi6h7gZQ0ACDhEeFTRVQrLVUcor@ZxidMedXly2G2JCC93AqGf7fGonKYmJLadis2pGtPfSDhohxNqwjM5HZ9pTZdpPZ7kY07fJyb5spzc70BQ "Python 3 ‚Äì Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
a=>a.map(v=>(++i,c+=v)<m?0:o=[...a.slice(i),...a.slice(0,i,m=c)],i=c=m=0)&&o
```
[Try it online!](https://tio.run/##dY0xDoMwDEX3niITiUWIYKV1OIiVIUqhCgKCGsT1aaBLhehiyf/5@fd2tdG9/bwUU3i2W4ebRW3VaGexohZ57qXLcYXH2JR1QFJKWRUH71rhQf5spfRyRAdGenQ4YglZFrYFI@pO7Fo0x1fHULM0EBknzhpWVKxmFcCZprw5TmrGDQfVBz8JzuHmwhTD0KohvMQiOCUI93NqDNFVToYSujQSuv5FtFvJ@9N0QPr2bR8 "JavaScript (Node.js) ‚Äì Try It Online")
Input an array of \$\pm 1\$.
Count each `[` as \$-1\$, each `]` as \$+1\$. Find out the position \$p\$ where \$\sum\_{i=0}^{p}a\_i\$ has max value. And rotate it there. I believe this approach may be golfed more bytes, but I didn't find out an obvious way.
[Answer]
# [Red](http://www.red-lang.org), 50 bytes
```
func[s][while[error? try[load s]][move s tail s]s]
```
[Try it online!](https://tio.run/##RY09DsIwDIX3nsLKzgUY4A6sTx7SxFEjlaZyAqinDy6o4Mnf@9FTif0mETykM/X0WAIq4zXlWSCqRa/UdMNcfKTKjHt5ClVqPs/GlXsqKj5MNBIGsnNg930sDXdoMDp0o18I2D1z/60PY@8yVs1LQyjrZgPudHGUaGTubw "Red ‚Äì Try It Online")
### Explanation
[Red](http://www.red-lang.org) uses brackets for its `block!` datatype so every set of balanced brackets is a valid value. That's why I'm trying to load the string holding the brackets (that is to convert the string to a Red value) and if this throws an error, I move the leading character of the string at the tail.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes
*-2 thanks to [@Command Master](https://codegolf.stackexchange.com/users/92727/command-master).*
```
Œ∑OWk>._
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3Hb/8Gw7vfj//6N1DXUUQBhBGcYCAA "05AB1E ‚Äì Try It Online") Takes input as a list, with `1` for `[` and `-1` for `]`.
```
Œ∑OWk>._  # full program
     ._  # rotate...
         # implicit input...
     ._  # left...
    >    # 1...
   k     # -based index of...
  W      # maximum...
Œ∑        # cumulative...
 O       # sum...
Œ∑        # of...
         # implicit input...
   k     # in...
Œ∑        # cumulative...
 O       # sums...
Œ∑        # of...
         # implicit input...
     ._  # times
         # implicit output
```
`>._` can also be `._√Ä` with no change in functionality.
As a bonus, this works too!
```
Œ∑OWk>
._.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~110~~ 108 bytes
```
x=>{for(s=x,i=0;++i<x.length;s=s.slice(1)+s[0])for(y=0,h=s;++y<s.length;h=h.replace('[]',''))if(!h)return s}
```
[Try it online!](https://tio.run/##NcpBDsIgEADAr@gJCJXUc7t@hHAgdVswhG1YNG2Mb8d6cM7z8C/PU4lrvWS6YyNoG9zeMxXJsHUR@kHrOG4mYV5qGBjYcIoTyqvSbHunfnWHvgvAR91H/tcAwRRckz@ysE50QigVZ3kOqmB9lnziT5soMyU0iRZJUjhnnbXHa18 "JavaScript (Node.js) ‚Äì Try It Online")
This was very tricky, but I managed to abuse for loops a lot.
Explained:
```
x=>{                      // declare function
  for(                    //repeat:
    s=x,i=0;              //initiate string and looper to 0
    ++i<x.length;         //repeat while i+1 is less than string length, and increment i at the same time
    s=s.slice(1)+s[0]     // loop string along by 1
  )
    for(                  //repeat:
      y=0,h=s;            //initiate looper, and string to use to check if matching
      ++y<s.length;       //repeat while incremented y is less than string length (since there are only so many brackets)
      h=h.replace('[]','')// remove a single occurrence of [] from h - if this is repeated enough and brackets match, it will eventually be empty.
)
if(!h)return s           // if h is an empty string, this means s's brackets match, so return s. No point in dealing with invalid input since it will always be valid.
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
->s{s.rotate (0..s.size).min_by{|r|s[0,r].sum}}
```
[Try it online!](https://tio.run/##JYxLCsMwDESv4k0ggUYkq67aiwhRLHAgi7TBciiu5bO7SruZzxuYeHBuy62NdykC8ZV8Cq6fAARk/YQBtvX54Fw0quB0iQRybLW23XXvHskRITokNHemaAjx7EbO9ZeM2JHfi3pd0APnFOQPWOeRu2ul2r4 "Ruby ‚Äì Try It Online")
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), 13 bytes
```
{(1+*>+\x)!x}
```
[Try it online!](https://tio.run/##LcoxDoAgDAXQ3VPULorEGFZM9CC1g4uQkOhKQjg7FnTq/@83zOG5z1Ium0ajp00fUfUxF2fTbDQSMO6LjbnzdmzNaNUlDxc4iHkQY1wBmYnqJSaJTSR@G1FV8f@zFUFU5QU "K (Kona) ‚Äì Try It Online")
Uses -1 for [ and 1 for ].
A port of [Ad√°m's APL answer](https://codegolf.stackexchange.com/a/221310/75681)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
(.*?)(((<)|(?<-4>>))+)$
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZIQHZtgY/dfQ0/LXlNDQ8NGs0bD3kbXxM5OU1NbU4VLxUjF8H8IUAVQ3f/oWK7Y2OhorujYaCDNBSSjgULR0SA@UAQkC2YBRQA "Retina 0.8.2 ‚Äì Try It Online") Takes input as a string of `<`s and `>`s but link includes test suite which maps `[` and `]` for convenience. Explanation: This is a fairly direct application of .NET balancing groups. The `<` character is captured into group `$4`, which works like a stack. Meanwhile, `>` characters can only be matched by popping `<`s from the `$4` stack. This ensures that we take the first suffix of the input that does not contain a mismatched `>`. (It can of course have a mismatched `<` but that will be matched by a `>` in the prefix.) It then remains to exchange the prefix with the suffix.
[Answer]
# [PHP](https://php.net/) < 7 -F, 59 bytes
```
for($a=$argn;eval($a)!==null;)$a=substr($a,1).$a[0];echo$a;
```
[Try it online! (not working, PHP 7)](https://tio.run/##K8go@G9jXwAk0/KLNFQSbVUSi9LzrFPLEnOAPE1FW9u80pwca02gTHFpUnEJSI2OoaaeSmK0Qax1anJGvkqi9f//tbW11SBYXf0vv6AkMz@v@L@uGwA "PHP ‚Äì Try It Online")
[Try with onlinephpfunctions (working PHP 5.6)](http://sandbox.onlinephpfunctions.com/code/1ae2ca44e65132d5718163fd5da26656281ae574)
Inspired by [Jo King's answer](https://codegolf.stackexchange.com/a/221299/90841). Works with `{}` braces instead of square ones.
[From the docs](https://www.php.net/manual/en/function.eval.php):
> 
> eval() returns null unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned false and execution of the following code continued normally.
> 
> 
> 
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 89 bytes
This solution uses parenthesis rather than brackets.
```
for($n=$args){try{$n-replace"\(",",@("|iex *>0;break}catch{$n=-join$n[1..$n.Length+0]}}$n
```
[Try it online!](https://tio.run/##RY1da8IwFIbv@yuknM2TWUu9lozArgaDCrvsitR4anVdWtIUN2J@e5fIpnfvc96P03dn0kNDbTtBze1UdxpBcaj0YWDW6B8LaqmpbytJ8QfGSZwIjC9H@p49PWfrnabq08nKyMYH@fLUHRWoYpWmoNI3UgfTLLLSOVCTi8BILjASOEc2Z0kQjCH@SWTo6f/u6RZCDJ53760rY@hGLAJNgx9m4cHlwQZc8GLz/jIOpvvKdyeSpixyvSdN@1LYV9WPhsO2yMp1PpoA@Aj1TGyZc9e16Rc)
## Bonus [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), Regex-Based 129 127 bytes
Sure, the other way is shorter, but how often do I get a chance to use my balanced-bracket-matching regex?? Almost never!
```
for($n=$args;!($n-match'((\[(?=[^\]]*(?<s>\]))|\k<s>(?<-s>))+?(?(s)(?!)))*'-and$n-eq$Matches[0])){$n=-join$n[1..$n.Length+0]}$n
```
[Try it online!](https://tio.run/##RY5BT4NAEIXv/AqbrLJThNRzu4XEk4kGE4/D2iAspbVd6u4SD5TfjrNN1dv75s17M6fuWxnbqsNhYo0YpqYznGnBSrO1yxnJ@Fi6qg05L5CnAt8LKec8Xdl1IQHOxScpwtiuAaKUp9wCT2cAMA/jUteUV1/sxVcoiwuKDNQe77udZhofkoTp5FnprWujhRyZnsaAuUpkPMh4iDKEey@kRLxKlEj0Oyf6W0L0Hrn/qQujzwYQMKMsFYM/cL4dPEYCX98ee@u6Y/6xV5WTmJtaGVXLbHjSp94JtqGvl3nvPPA71txkGxjHS9v0Aw "PowerShell ‚Äì Try It Online")
[Answer]
# JavaScript, 56 bytes
```
q=>q.map(async _=>q.push(q.shift())|eval(q+'')|alert(q))
```
[Try it online!](https://tio.run/##TYxbDoMgEEX/XUX/mElTNtDgRiakEopVQ0EETZq4d4rGPv7uua9BLSrqqR/Txfm7ycqaKQktau1d9NZw6x@g@eB71zR4rVqRg6gDf6oRVHw5fbptOM6xg8Bj17cJEFezKAvhzBiu@yMExJxEFHULxDmPEqsEjCQrn0VISXRIklTo4xf6loi2rKS/1c70tz3q@Q0 "JavaScript (Node.js) ‚Äì Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~87~~ 86 bytes
Inspired by [Zaelin Goodman](https://codegolf.stackexchange.com/a/221331/80745)
```
param($n)$n|% t*y|%{($n=($n|% S*g 1)+$n[0])}|?{try{$_-replace'\(',',(0'|iex;1}catch{}}
```
[Try it online!](https://tio.run/##RZDNboMwEITvfgorcup1SqTkjFAj9dRTqnKkKKJm81MRQo1RExk/OzVgqE8zs/vNSq5uv6jqMxZFx46R6apMZVdgpWBlu6R69WiXxtkIBh@vTnQrnlmZbFJh2xej1cOww1phVWQS@SfwgAew4e0F7@HWykzLs7G2s4TsgJAAOAhO/Qto70SfCgHA/1MQPgfh5DgZ83niFPiuoWdgPDu1wgC4wE9m528O1sV8bOjltOs1zOS47EgiqPsJQwirtbqUp4DhvUKpMacRZQfCFNZNoWvnntiR@i2SvMevTa1v1/3Xt9tOk73KUWGe7kzcSIl1DywmeEHX@OPsVL0I6VtZNbo/MRaG9GO@M1Hul233Bw "PowerShell ‚Äì Try It Online")
The script returns all solutions.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
{:k[√∏o|«ì
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%7B%3Ak%5B%C3%B8o%7C%C7%93&inputs=%27%5D%5D%5D%5B%5D%5B%5D%5B%5B%5B%27&header=&footer=)
Takes as a string of `[]`.
```
{        # While...
    √∏o   # Removing until no change...
  k[     # The string `[]`
 :       # From the top of stack
    √∏o   # Eventually yields a truthy value (i.e. non-balanced)
      |«ì # Rotate left.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 147 bytes
```
def f(u):
 k=set()
 for x in permutations(u):
  s=''.join(x)
  try:eval(s)
  except:pass
  else:k.add(s)
 print "\n".join(k)
from itertools import*
```
[Try it online!](https://tio.run/##PYsxDsMgDEX3nMJiiemQoSNSbtIFNUalSTACt0pOTyFpu/n5vR93eXC4ljKRA4cvbTqYx0yCugPHCTbwASKl9SVWPId8NpDHvh@e7ANutQRJu6G3XTA3ou1OUUy0OTdaMpl5sNN02Jh8EFC3oM79rDuXeAUvlIR5yeDXyEkuxaFCrapGpTXieaHGCt9vhV@B2Ex1/8WB2HblAw "Python 2 ‚Äì Try It Online")
Slow, permutation based approach
]