Alternesting, is the act of taking a string and nesting it in alternating brackets. Here is how you alternest a string.

  • For a string of length N, take the center N characters, and surround them in parenthesis. So if our string was Hello world! (12 characters), we'll end up with

    (Hello world!)
  • Then, take the remaining center n-2 characters, and surround them in square brackets. In this case, the center 10 characters are ello world, so the next iteration is:

    (H[ello world]!)
  • As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between () and []. Here are the last steps:

    (Hello world!)
    (H[ello world]!)
    (H[e(llo worl)d]!)
    (H[e(l[l(o[ w]o)r]l)d]!)

    Since there are only two characters left in the middle on the last iteration, we stop. Our final string is

    (H[e(l[l(o[ w]o)r]l)d]!)

    Note how there are two characters in the middle brackets. This happens when the input is an even length. If the input was an odd length (for example, Hello, world! with a comma added), we would have only one character in the middle:

    (H[e(l[l(o[,( )w]o)r]l)d]!)

For today's challenge, you must write a program or function that takes a string as input, and alternests it, outputting the new string. You can take input and output in any reasonable format you like. The input will always be at least one character long, and will only contain printable ASCII. You can also assume that the input will not contain any parenthesis or square brackets. For traditional languages, this shouldn't matter too much, but it might make it easier for some esoteric languages.

As usual, this is a competition, so try to make the shortest possible answer in the language of your choice. Have fun!

Test IO

#Input                      #Output

"Alternesting is fun!"  --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!)
"PPCG"                  --> (P[PC]G)
"Code-golf"             --> (C[o(d[e(-)g]o)l]f)
"4 8 15 16 23 42"       --> (4[ (8[ (1[5( [1]6) ]2)3] )4]2)
"a"                     --> (a)
"ab"                    --> (ab)
"abc"                   --> (a[b]c)
  • \$\begingroup\$ Related \$\endgroup\$
    – DJMcMayhem
    Commented Jun 28, 2017 at 17:44
  • \$\begingroup\$ Must we always start with parentheses (()) or can we start with brackets ([])? \$\endgroup\$ Commented Jun 28, 2017 at 17:49
  • \$\begingroup\$ @totallyhuman It should always start with parentheses () \$\endgroup\$
    – DJMcMayhem
    Commented Jun 28, 2017 at 17:50
  • 1
    \$\begingroup\$ Proposed testcase: HelloWorld. \$\endgroup\$ Commented Jun 29, 2017 at 8:28
  • \$\begingroup\$ Also, are trailing spaces allowed? \$\endgroup\$ Commented Jun 29, 2017 at 9:00

25 Answers 25


Python 3, 70 69 65 bytes

-1 byte thanks to @Uriel
-4 bytes thanks to @xnor

f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b]

Try it online!


C, 143 137 135 bytes


Try it online!


// Function (and variable) declaration.

// Start the loop and initialize the variables. The loop terminates
// when the NUL-terminator of the string is reached.
for(k=i=0,l=strlen(s);*s;<this part saved for later>)

// Check if we have reached the middle of the string. Because of the
// short-circuiting of the conditions, we don't need to use an 'if'
// statement here; if a condition is false, no further conditions
// are evaluated.

// Equivalent to '!(l%2)', but one byte shorter. Checks if the length
// of the string is even.

// If we have reached the middle and the length of the string is even, 
// we'll need to skip one bracket, so we'll print the current character
// of the string and increment the pointer. Also we increment 'l' to
// avoid this getting done more than once, and give 'k' a non-zero
// value.

// The following is inside the 'increment' part of the 'for' loop.
// We print two characters. The first one is a bracket and the second
// one is the current character in the string.

// The type of bracket is  chosen depending on the value of 'i'. A 
// character from the string "([])" is selected with the index 'i%2 + 2', 
// if we have reached the  middle of the string, and with index 'i%2', if
// we haven't.

// The exact part where this change happens depends on the parity of 
// the string length, so we use 'k' to signal if the length is even or 
// odd. If the length is odd, 'k==0', so '+!k' is the same as '+1'.  
// Otherwise 'k' is non-zero, so '+!k' is the same as '+0'.

// Output the final ')'.
  • \$\begingroup\$ If I remember C correctly, variables declared globally are initialised to 0. Thus, you shouldn't need the k=i=0,. I might be wrong. See this SO answer \$\endgroup\$
    – Tas
    Commented Jun 28, 2017 at 21:29
  • \$\begingroup\$ @Tas You are indeed correct, but functions have to be reusable to be valid submissions, so the variables need to be initialized inside the function. \$\endgroup\$
    – Steadybox
    Commented Jun 28, 2017 at 21:36

Retina, 52 bytes


Try it online! The first stage inserts pairs of parentheses between each pair of input characters, while the second and third stages correct alternate parentheses to brackets.


JavaScript (ES6), 69 68 62 bytes

-6 thanks to @Shaggy


Try it online!

  • 1
    \$\begingroup\$ 62 bytes \$\endgroup\$
    – Shaggy
    Commented Feb 15, 2023 at 18:01
  • \$\begingroup\$ @Shaggy Wow! This answer is quite old ... Thanks :) \$\endgroup\$
    – Arnauld
    Commented Feb 15, 2023 at 18:38

Sed, 78

Score includes +1 for -r option passed to sed.


Try it online.


V, 25 26 25 bytes

1 2 bytes off thanks to @DJMcMayhem


Try it online!

Borrowed some of @udioca's ideas. Also finally used the surround plugin included in V for an answer, although it may not have been the best way, who knows. The plugin does NOT want to be used.


00000000: e3e1 0a6b f2e9 286c 6ce9 5b6c 6cf2 6af2  ...k..(ll.[ll.j.
00000010: e129 6868 e15d 6868 f2cd ce              .)hh.]hh...


-> |abcdefg      (the input, where | is the cursor)
ò              ' recursively
 C()           ' (C)hange from the cursor to the end of the line to '()'
-> (|)    (where | is the cursor)
     P         ' (P)aste the changed bit (what was there) left of the cursor
-> (abcdef|g)
      é        ' nsert a newline
-> (abcdef
%              ' Goto the previous matching parenthese
-> |(abcdef
 ll            ' Move two characters right
-> (a|bcdef
   ò           ' End recursive loop (it will break on ll when there are no characters left
-> (a(b(c
    Íî         ' Remove all newlines
-> (a(b(cd)e)f|)
ò              ' Recursively
 F)            ' Go backwards to the next )
-> (a(b(cd)e|)f)
   %r[         ' Go to the matching paren and (r)eplace it with [
-> (a|[b(cd)e)f)
               ' Go back to the previous cursor location
-> (a[b(cd)e|)f)
       r]      ' (r)eplace this paren with ]
-> (a[b(cd)e|]f)
         ;     ' repeat F)
-> (a[b(cd|)e]f)
               ' implicitly end recursion
  • \$\begingroup\$ Wow, nice job! I was stuck at 29 bytes but missing a bunch of edge cases. This is a pretty sweet answer. You can save one byte by using ; instead of the last f) Try it online! \$\endgroup\$
    – DJMcMayhem
    Commented Jun 28, 2017 at 19:03
  • \$\begingroup\$ It's actually broken right now because of spaces, I'm going to delete and fix \$\endgroup\$
    – nmjcman101
    Commented Jun 28, 2017 at 19:04
  • \$\begingroup\$ @DJMcMayhem Can I see your 29 byte one? Unless you plan to golf it under me and compete, which I wouldn't be surprised about :) \$\endgroup\$
    – nmjcman101
    Commented Jun 28, 2017 at 19:13
  • \$\begingroup\$ It doesn't work, so I don't mind showing you it: tio.run/##K/v///… Oh, and BTW: chat.stackexchange.com/transcript/message/38434285#38434285 :) \$\endgroup\$
    – DJMcMayhem
    Commented Jun 28, 2017 at 19:17
  • \$\begingroup\$ :( doing alternating () and [] is a byte shorter but way less cool \$\endgroup\$
    – nmjcman101
    Commented Jun 29, 2017 at 1:51

Haskell, 96 91 81 79 77 bytes

(l:r:a)!k|[x]<-k=[l,x,r]|x:y<-k=l:x:a!init y++[last y,r]|2>1=k

Try it online!

  • 1
    \$\begingroup\$ You can drop the parents around (x:y) and (init y). k==""="" is shorter as k==""=k. \$\endgroup\$
    – Laikoni
    Commented Jun 28, 2017 at 23:00
  • 1
    \$\begingroup\$ Save some more bytes by changing cycle["()","[]"] to just "()[]": Try it online! \$\endgroup\$
    – Laikoni
    Commented Jun 28, 2017 at 23:02
  • \$\begingroup\$ @Laikoni great suggestions,thanks \$\endgroup\$
    – bartavelle
    Commented Jun 29, 2017 at 5:12
  • 1
    \$\begingroup\$ Good catch that keeping cycle is even shorter. You can still remove the parenthesis around (init y). \$\endgroup\$
    – Laikoni
    Commented Jun 29, 2017 at 6:40
  • 1
    \$\begingroup\$ You can move the case k==""=k to the end and change it to 0<1=k. \$\endgroup\$
    – Zgarb
    Commented Jun 29, 2017 at 13:35

Ruby, 79 77 bytes

-2 bytes thanks to @Value Ink

(z/2+z%2).times{|i|s.insert k=i*2,'(['[i%2]

Try it online!

  • \$\begingroup\$ s.insert k=i*2,'(['[i%2];s[~k]+=')]'[i%2] to save 2 bytes. Try it online! \$\endgroup\$
    – Value Ink
    Commented Jun 28, 2017 at 22:00

Javascript(ES6) 110 105 bytes

Thanks to @powelles for reminding me about x%y<1.

Thanks @Luke for a-b?y:x


let f=i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d==b?'':(d%1==0?!e:e)?')':']')).join``
<input onkeyup="result.textContent = f(this.value)"/>
<p id="result"></p>

The first thing in understanding this beast is ungolfing it:

function alternest(input) { //input is i in the original
  let inputArray = Array.from(input); //the [...i] section
  let result = inputArray.map((item, index, baseArray) => { //result is an added helper variable
    let middle = input.length / 2 - 1, //the middle of the string
        alternate = index % 2 == 0; //should you alternate from '(' and '[' or ')' and ']'

    let symbol; //the alternating symbol

    if(middle > index) { //if its opening braces
      symbol = alternate ? '[' : '(';
    } else if(middle < index) {
      if(middle % 1 === 0) //if middle is a whole number
        alternate = !alternate; //reverse alternate
      symbol = alternate ? ')' : ']';
    } else { //if middle === index
      symbol = ''; //there's no symbol in the center for even alternests
    return item + symbol; //convert the array item into the item and symbol

  return '(' + result; //add the first symbol.

Almost every line is a part of the golfed version, so stepping through:

Line 1: The function statement becomes an arrow function, renaming input to i. Becomes i=>.

Line 2: Array.from is the new, proper way of converting a string into an array, and what we use in on this line. However along with it, the spread operator is a cheaper way than the old .split('') way, to do it, which is what is used in the golfed version. Ends up as [...i].

Line 3: .map loops through an array, giving you three arguments: item(a in the golfed), index; golfed as b, and baseArray or c. While we only care about item and index, we kept baseArray(see line 4 for why). Golfs to .map((a,b,c,...)=>....

Line 4: The variable middle, the or the argument d in the golfed version is created to save a few bytes when it is repeated. The argument c had to be kept for argument d to be created. Is converted to (...,d=i.length/2-1,...).

Line 5: The variable alternate, or argument e is used to check what character it was on "(" or "[" or if it was past the middle, ")" and "]". b%2<1 is equal to b%2==0 because it can't be anything less than 1, but 0 in this case. Equals (...,e=b%2<1).

Line 6: A helper variable to allow me to convert the ternary operators to if statements. Isn't anything in the actual codegolf.

Lines 7-8: If the index is less than the middle of the string set the symbol to an alternation of "[" and "(". Equates to d>b?e?'[':'(':....

Lines 9-12: Else (if index is greater than middle), check if middle is a whole number, if so switch the alternation. Then set the symbol to an alternation of ')' and ']'. Obfuscated to (d%1==0?!e:e)?')':']'.

Lines 13-15:If the in the middle set the symbol to an empty string. This doesn't apply to odd alternesters, because middle has a decimal. Becomes: d==b?'':....

Line 16: Joins the character array back into a string. Equates to .join``.

Line 17: Returns the starting symbol "(" and the result. Correlates to '('+....

  • \$\begingroup\$ For some simple wins you could change %2==0 to %2<1 and use [...i] instead of i.split \$\endgroup\$
    – powelles
    Commented Jun 28, 2017 at 19:21
  • 1
    \$\begingroup\$ Thanks @powelles I've been working on an explanation more than a fully golfed answer, so that hasn't made it into an edit yet. I already had the [..i] idea, but I forgot about %2<1 thanks. \$\endgroup\$ Commented Jun 28, 2017 at 19:24
  • \$\begingroup\$ b%2<1 could be replaced by !b%2 \$\endgroup\$
    – Luke
    Commented Jun 28, 2017 at 21:55
  • \$\begingroup\$ Also, d==b?x:y could become d-b?y:x and d%1==0 could become !d%1. \$\endgroup\$
    – Luke
    Commented Jun 28, 2017 at 22:01
  • \$\begingroup\$ Unfortunately because of order of operations !d%1 only works with parentheses: !(d%1), and it doesn't shave off any bytes. I forgot that 0 was the only falsy number, for some reason I thought -1 was the falsy one. Correct me if I'm getting something wrong about the second one. \$\endgroup\$ Commented Jun 28, 2017 at 22:38

Jelly, 23 21 bytes


Try it online!

LHĊRị           - helper function. Takes inputs of the input string and list of brace types
L                 - length of the input string
 HĊ               - number of parenthesis/brackets facing a single direction
   R              - range
    ị             - indexed into right argument: list of brace types ')]' or '(['

ç⁾)]żUFUż@ç⁾([$ - main function 
ç⁾)]              - get list of left-facing parentheses/brackets
    żU            - zip to the end (U) of the input string
      FU          - move the beginning of the string back to the beginning
        ż@        - zip with (to the start of the string):
          ç⁾([$   -the list of right-facing parentheses/brackets to the beginning

-2 bytes thanks to @EricTheOutgolfer


SCALA, 140 138 chars, 140 138 bytes

I'm sorry I couldn't do better ... I'm sure there are many ways to improve it. Still:

val n=s.length-1
var l=""
var r=""
for(i<-0 to n/2){l+=(if(i%2<1)"("else"[")

Try it online!

Thanks for this challenge, that was quite hard for me.

EDIT : -2 bytes thanks to Mar Dev.

PS : I will ask something though. I understand why THIS CODE keeps duplicating the central char of my string if I have an odd length (I just don't check and add it twice, in both l and r strings). But why do I get a pair of parenthesis when I try correcting it like THAT? I don't understand at all.

  • 1
    \$\begingroup\$ You can change the i%2==0 to i%2<1 to save two bytes. \$\endgroup\$ Commented Jun 29, 2017 at 1:47

Perl, 77 74 (73 + 1) bytes

Regular expressions are glorious things. Run with the -p command line flag.

$x=qr/[^]()[]/;$z=qr/(^|$x)\K($x+)($|$x)/;s/$z/[$2]$3/ while s/$z/($2)$3/

05AB1E, 31 bytes


Try it online!


With examples for input: abcd / abcde

2ä`                              # split input to 2 separate parts on stack
                                 # RESULT: 'ab','cd' / 'abc', 'de'
   R                             # reverse the second part
    ð«                           # append a space
      „)]                        # push the string ")]"
         Ig©×                    # repeat it len(input) times
             ø                   # zip with the second part of the input string
              RJ                 # reverse and join to string
                                 # RESULT:  ' )c]d)' /  ' )d]e)'
                ®Èƒ¦}            # remove the first (1,2) chars for (odd,even) length input
                                 # RESULT: 'c]d)' / ')d]e)'
                     s           # swap the first part of the input string to top of stack
                      „([®×      # repeat the string "([" len(input) times
                           sø    # zip with first part of input string
                                 # RESULT: ['(a', '[b'] / ['(a', '[b', '(c']
                             Jì  # join to string and prepend to the second part

C++ 14, 154 145 134 bytes

(Thanks to ideas by ceilingcat for extra bytes 145->134)


#include <regex>
using S=std::string;S L(S i,int b=1){int l=i.size();return"(["[b]+(l<3?i:i[0]+L(i.substr(1,l-2),!b)+i[l-1])+"])"[b];}

C++ 14, 177 bytes


auto l(string s){int z=s.length();string r(z*2+z%2,'-');int i=0;for(;i<z;i+=2)r[i]=i/2%2?'[':'(',r[i+1]=s[i/2];for(i=z;i<2*z;i+=2)r[i]=s[i/2],r[i+1]=(i+1)/2%2?')':']';return r;}

Ruby, 57 bytes

f=->s,i=0{a,*b,c=s;a ?["(["[i],a,*f[b,~i],*c,")]"[i]]:''}

Try it online!

Recursive function similar in spirit to ovs's Python answer. Inputs and outputs arrays of characters.

Note that we could shave off 3 more bytes, and in the test suite on TIO, where we join the arrays back to strings, the visible result would look unchanged:

f=->s,i=0{a,*b,c=s;a ?["(["[i],a,f[b,~i],c,")]"[i]]:p}

However, this would produce nested arrays and nils in the raw output, which is probably too weird for a "reasonable" output format.


Pyth, 42 (!) bytes


Test it online! The input must be quoted.


M                                             # Define a function g with arguments G and H
 ?!lHH                                        # If len(H) == 0, return H. Otherwise...
      +@,\[\(G                                # Concatenate [ or ( to...
               +hHg!GPtH                      # ...to H[0] concatenated to g(not(G), H[1:-1]), itself concatenated...
              +          ?qlH1keH             # ...to H[-1] if len(H) != 1, otherwise to "" (that's for odd length input strings)...
                        +        @,\]\)G      # ...and to that concatenate ] or ).
                                        g1    # Call g(True, Q). Q is implicit input

So basically I progressively remove the head and end of H (being the input string in the beginning) while concatenating the parentheses/brackets. G is just a boolean which remembers if I must use brackets or parentheses.


05AB1E, 49 42 bytes


Try it online!


PowerShell, 125 119 111 bytes


Try it online!

Previous version*


*Thanks @Digital Trauma.


QuadR, 82 bytes

(81 bytes +1 for flag)


Try it online!


AWK, 118 bytes

{b=")";for(j=l=length(c=$0);j>0;){x=substr(c,j--,1);b=(j>l/2?(((d=!d)?"]":")")x):j==l/2?x:((d=!d)?"(":"[")x)b}print b}

Tested with gawk, but it should work with any compliant awk interpreters

$ awk -f alternesting.awk <<< 'abc'

JavaScript, 101 bytes

Not a winner, but it was interesting to try the replace approach. This could definitely be improved, but it got out of hand quick...


Java (OpenJDK 8), 124 bytes

c->{String s="";for(int l=c.length-1,a=l/2;a>=0;)s=(a%2<1?"(":"[")+(a<-~l/2?c[a]+s+c[l-a]:c[a])+(a--%2<1?")":"]");return s;}

Try it online!



Stax, 25 bytes


Run and debug it


JavaScript (Node.js), 77 bytes

Not the best JS solution, but it could interest some people : this solution uses recursive calls with inversion of the 2 optional parameters at each step to alternate between () and []


Try it online!


Japt, 28 bytes

Initially inspired by Arnauld's solution.


Try it

V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U     :Implicit input of string U
V                                :Second input variable, defaulting to 0
 °                               :Postfix increment
  g                              :Index, 0-based & modular, into
   "()[]"ò                       :  Length 2 partitions of string "()[]"
          )                      :End indexing
           i1                    :Insert at 0-based index 1
             ¢                   :  Slice first 2 characters off U
              ?                  :  If truthy (non-empty string) return
               UÌ                :    Last character of U
                 i               :    Prepend
                  UÎ             :      First character of U
                    +            :      Append
                     ß           :        Recursive call with argument (V is passed automatically)
                      Us1        :          U sliced from index 1 to index
                         J       :          -1
                          :U     :  Else return U

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.