# Telescopic Parentheses

Consider a non-empty string of correctly balanced parentheses:

(()(()())()((())))(())


We can imagine that each pair of parentheses represents a ring in a collapsed telescopic construction. So let's extend the telescope:

(                )(  )
()(    )()(    )  ()
()()    (  )
()


Another way to look at it is that the parentheses at depth n are moved to line n, while keeping their horizontal position.

Your task is to take such a string of balanced parentheses and produce the extended version.

You may write a program or function, taking input via STDIN (or closest equivalent), command-line argument or function parameter, and producing output via STDOUT (or closest equivalent), return value or function (out) parameter.

You may assume that the input string is valid, i.e. consists only parentheses, which are correctly balanced.

You may print trailing spaces on each line, but not any more leading spaces than necessary. In total the lines must not be longer than twice the length of the input string. You may optionally print a single trailing newline.

## Examples

In addition to the above example, here are a few more test cases (input and output are separated by an empty line).

()

()

(((())))

(      )
(    )
(  )
()

()(())((()))(())()

()(  )(    )(  )()
()  (  )  ()
()

((()())()(()(())()))

(                  )
(    )()(        )
()()    ()(  )()
()


Related Challenges:

• Topographic Strings, which asks you to produce what is essentially the complement of the output in this challenge.
• Code Explanation Formatter, a broad generalisation of the ideas in this challenge, posted recently by PhiNotPi. (In fact, PhiNotPi's original description of his idea was what inspired this challenge.)

Huh, this got quite a lot of participation, so here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

# Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes


function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>

• Alternative title: De-Lisp-ify a string. :P – Alex A. Apr 20 '15 at 20:25
• Are there any restrictions on the color of the output? – Matteo Italia Apr 21 '15 at 20:20
• @MartinBüttner: nevermind, I found a cleaner way; let's just say that my previous idea would have shaved a byte leaving all the closed parentheses blinking blue over cyan... :-) – Matteo Italia Apr 21 '15 at 21:00
• @MatteoItalia oh god, I'm glad that didn't happen. ;) – Martin Ender Apr 21 '15 at 21:00
• @MatteoItalia: Post that version! It's worth seeing. – user2357112 supports Monica Apr 22 '15 at 4:28

h#('(':s)=h:(h+1)#s
h#(_:s)|k<-h-1=k:k#s
_#_=[]
g s=[do(c,i)<-zip s$0#s;max" "[c|i==h]|h<-[0..maximum$0#s]]


Try it online!

# Brain-Flak, 338 bytes

([]){(({})[()]<([{}][])([][()]){({}[()]<(({}<(({})(())){({}[()]<([{}]())>)}>{})<({}{})((){[()](<{}<>((((()()()()){}){}){})<>>)}{}){{}(({})<>)(<>)}{}(({})(())){({}[()]<([{}])>)}{}>{}<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)>)}{}{}<>((()()()()()){})<>>)}{}{{}}<>{{}{}(({})[((((()()()){}())){}{}){}]())}{}{({}<>)<>}<>


Try it online!

## Idea

The idea for this program is that we make a number of passes over the string. Each time we make a pass we keep track of a counter, we decrement the counter if we encounter a ( and increment it if we encounter a ). If ( brings it to -1 we copy it to the offstack and if ) brings it to zero we copy it to the offstack. Otherwise we just copy a space. We do this as many times as the length of the string starting the counter at 0 the first time and decreasing it each loop. This way we catch the different layers in order. When we are done we just trim characters until we reach a ).

# IDL 8.4, 173 177 bytes

This is similar enough to the formatter challenge that I had half a solution already. IDL is still a terrible golfing language, but I'm pretty happy with how this worked out.

read,(p='')&a=[0:strlen(p)-1]&c=strmid(p,a,1)&e=c.map(lambda(x,d:'('eq x:d++:d---1)))&print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a))&end


Un-golfed:

read,(p='') ;read a string from input
a=[0:strlen(p)-1] ;index array to the input
c=strmid(p,a,1) ;split the input into an array of 1-char substrings
e=c.map(lambda(x,d:'('eq x:d++:d---1))) ;for each substring, increment depth if ( and decrement otherwise, saving depth each time
print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a)) ;print an array of strings, each one including the parens in that depth level.
end ;end the script


# C#, 196 bytes

Very simple complete program that takes input via STDIN, and outputs to STDOUT. I should like to get rid of the S.Length, but haven't found a way that pays.

using Q=System.Console;class P{static void Main(){var S=Q.ReadLine();for(int i=0,c;++i<S.Length;){var r="";c=0;foreach(var k in S)r+=(c+=81-k*2)+k-40==i?k:' ';if(r.Contains("("))Q.WriteLine(r);}}}


It simply iterates over the input a number of times (input length - 1), keeping track of the parentheses "depth", and comparing it to the current iteration count (i) - if they match, then it adds the current parenthesis to a string, to be printed at the end of the iteration. Because more iterations may be done than necessary, it only prints the iteration result (r) if it contains a parenthesis.

using Q=System.Console;

class P
{
static void Main()
{

for(int i=0,c;
++i<S.Length; // can't be more than S.Length - 1 lines of output
)
{
var r=""; // reset result
c=0; // current paren depth
foreach(var k in S) // for each char in input
r+= // append something...
(c+=81-k*2) // move c
+k-40==i? // check if we should output the current char
k:
' '; // otherwise a space
if(r.Contains("(")) // only print if there is some content
Q.WriteLine(r);
}
}
}


# Python 2, 166 bytes

Not much to be said:

m,c,l=list(input()),0,[]
for j in m:c+=1if j=='('else-1;l+=[c-1if j=='('else c]
for i in range(max(l)+1):
t,p='',0
for q in m:t+=q if l[p]==i else' ';p+=1
print t


# MATL, 42 41 bytes

Uses current version (4.0.0) of the language, which is newer than this challenge (but the challenge was so attractive...)

j32-t8=2*1-TTo3X53$X+ZSYsP0hP1+wtn:wZ?32+c  EDIT (May 20, 2016): Try it online! with X+ replaced by Y+, according to version 18.0.0 of the language. ### Example >> matl j32-t8=2*1-TTo3X53$X+ZSYs0wh1+wtn:wZ?32+c
> ()(())((()))(())()
()(  )(    )(  )()
()  (  )  ()
()


### Explanation

The general idea is to use convolution to analyze pairs of consecutive symbols. There are four possible pairs:

• ((: the second symbol should be on a lower line than the first
• )): the second symbol should be on a higher line than the first
• () or )(: the second symbol should be on the same line as the first

When analyzing each pair, the line of the first symbol is already known, and the analysis tells the line of the second. Then the nex pair is analyzed, obtained by advancing one symbol, that is, with overlapping.

j           % input string
32          % ASCII code of space character
-           % subtraction. Will give 8 or 9 for '(' and ')'
t8=         % 1 for '(' symbols, 0 for ')'
2*1-        % convert into 1 / -1
TTo         % array [1 1] (for convolution)
3X5         % 'valid' flag for convolution
3$% specify three inputs for convolution X+ % convolution ZS % sign function Ys % cumulative sum 0wh % prepend a 0 1+ % add 1. This gives line number of each symbol wtn:w % Vector [1 2 ... n] where n is string length. Rearrange Z? % create (sparse) matrix with three inputs: row, col, val 32+c % add space code and convert to chat  # Charcoal, 12 bytes ＦＳ¿⁼(ι↘(«Ｍ↑)  Try it online! ### Explanation ＦＳ For each character in next input as string ¿⁼(ι If character is "(" ↘( Print "(" down and to the right - this is equivalent to printing "(" and moving down «Ｍ↑) Else move up and print ")"  # JavaScript (Node.js), 71 bytes x=>[...x].map((_,n,s)=>s.map(c=>(c=='('?n--:++n)?' ':c).join).join   Try it online! # JavaScript (Node.js), 85 bytes, just enough lines x=>[...x].map((_,n,s)=>(Q=s.map(c=>(c=='('?n--:++n)?' ':c).join)<1?'':Q+ ).join  Try it online! • Invalid, "You may optionally print a single trailing newline." – ASCII-only Apr 26 '18 at 4:53 # Haskell, 117 114 bytes f(y:b)|a<-sum[1|y=='(']=a:map(+(2*a-1))(f b) f[]=[] p s=[[last$' ':[a|b==i]|(b,a)<-zip(f s)s]|i<-[1..maximum$f s]]  Try it online! # Japt, 13 bytes y_ùZ<')?°T:T´  Try it ## Explanation y_ :Transpose, pass each column Z through a function and transpose back Z<') : Is Z less than ")", i.e., is Z equal to "("? ? : If so °T : Prefix increment variable T (initially 0) : : Else T´ : Postfix decrement T ù : Left pad Z with spaces to length T  # Retina, 65 bytes ./\S/{*\$$((?<-2>(\()*$$)*)\) ($.1* )
$$((?<-2>(\()*$$)*)\)
$1  Try it online! Note: Trailing space. Link includes test cases. Explanation: .  Don't print the spaces left over at the end. /\S/{  Repeat until there are only spaces left. *\  Print the result of this substitution without changing the current value. $$((?<-2>(\()*$$)*)\) ($.1* )


Match pairs of balanced parentheses and replace their content with a run of spaces of the same length.

$$((?<-2>(\()*$$)*)\)
$1  Match balanced parentheses and replace the outer pairs with spaces. For Retina 0.8.2 you have the choice of this 60 byte code: {*$$((?<-2>(\()*$$)*)\) ($.1$* ) $$((?<-2>(\()*$$)*)\)$1


Try it online! Note: Trailing space. Link includes test cases. Explanation: The differences are as follows:

• Retina 0.8.2 doesn't have a while loop, only a convergence loop. However, this ends up printing blank lines while waiting for the loop to converge.
• Retina 0.8.2 uses * for much the same effect as .*\.
• Retina 0.8.2 uses $* instead of * in the replacement. Alternatively, if the blank lines are a problem, you can use this 92 byte code: {.+$
$&¶$&
$$((?<-2>(\()*$$)*)\)(?=.*¶.*$) ($.1$* ) $$((?<-2>(\()*$$)*)\)(?=.*$)
$1 ¶ +$



Try it online! Link includes test cases. Explanation:

{


Repeat until the value converges.

.+&¶$&  Duplicate the last line. $$((?<-2>(\()*$$)*)\)(?=.*¶.*$)
($.1$* )


Match pairs of balanced parentheses on what used to be the last line and replace their content with a run of spaces of the same length.

$$((?<-2>(\()*$$)*)\)(?=.*$)$1


Match pairs of balanced parentheses on the last line and replace the outer pairs with spaces.

¶ +\$



Delete the last line if it's only spaces. This allows the loop to terminate.

# C, 949997 96

i,j,k,l;f(char*s){for(l=0;!i--;l-=puts(""))for(j=0;k=s[j++];putchar((k&1?--l:l++)?32:k))i&=l<2;}


Pure C version that doesn't use the consoles escape codes. Ungolfed:

i,j,k,l;                 // stop,iterator,current char,level
f(char*s){
for(l=0;               // reset level
!i--;              // stop ? return : stop = 1;
l-=puts(""))      // new line + next level
for(j=0;
k=s[j++];        // for each char
putchar(
(k&1?--l:l++)  // char == 41 ? prev level : next level
?32:k))        // only print brackets at level 0
i&=l<2;            // if level > 1 then don't stop
}


Try it online!

Changelog:

• +5 Byte Temporary fix to match rules
• -2 Byte Switch !i++ to !i-- drops the need to reset i
• -1 Byte Switch puts(""),--l to l-=puts("") Thanks to @ceilingcat
• I'm unable to find the relevant meta-post, but I'm pretty sure functions should be self-contained when run multiple times. So I think you should add i=j=k=l=0 to your code instead of resetting them in your main-method. I'll see if I can find the meta-post to explain it more clearly though, but I've had other people make these kind of comments on my answers in the past.. Nice answer nonetheless, so +1 from me. – Kevin Cruijssen Apr 26 '18 at 8:31
• @KevinCruijssen Here it is Edit: mwahahaha – Jo King Apr 26 '18 at 8:34
• Found the meta-post, and here another relevant one. EDIT: @JoKing You beat me to it by 10 sec. ;) – Kevin Cruijssen Apr 26 '18 at 8:34
• @KevinCruijssen A damn you're right what a sad day. Temp fix it at the cost of 5 byte. Hopefully I can get rid of some of them again. Ideas ? ;) – Christoph Apr 26 '18 at 8:49
• @Christoph Unfortunately I don't see anything to golf (although there might of course be). I'm not too skilled in C to be completely honest. It seems already pretty well-golfed to me, hence the upvote I gave. ;) – Kevin Cruijssen Apr 26 '18 at 8:55

# Japt-Rx, 17 bytes

¬£®¥'(?Y´:°Y ?S:Z


Try it online!

### Unpacked & How it works

Uq mXYZ{UmZ{Z=='(?Y--:++Y ?S:Z

Uq      Convert the input string into array of chars
mXYZ{   Map with the function...
Here, Y (index) is used as the desired level of "telescoping"
UmZ{      Map on the original input string with the function...
Z=='(?      If this char is "("...
Y--:          Decrement Y
++Y           Otherwise, increment Y
?           If Y is nonzero (i.e. this char is *not* at desired level)...
S:            Replace with a space
Z             Otherwise, use the char as-is

Flags:
-R      Join the resulting array with newline
-x      Trim the resulting string on both ends


Ported from @l4m2's JS solution. It actually fits into Japt's built-ins quite nicely, and trailing whitespaces can be conveniently removed with the use of -x flag.

# VIM, 101 bytes

↵ = Enter

qwlmto<esc>t@wq@w:s/()/(*)/g↵:set ve=all↵:set nows:↵set nosol↵qqvi)ygvr jPk/(↵@qq@qjjdGqeGl?*↵<C-V>ggoGr|@eq@e:%s/|//↵