The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.


Hi, world


Test Cases

Hi, world! Hello

d! H

Lorem ipsum dolor sit amt

m dol
or si
t amt




  • This is , so shortest answer in bytes wins! Tiebreaker is most upvoted answer.
  • Standard loopholes are forbidden.
  • Can we assume that the input will never have new lines? – MayorMonty Aug 6 '16 at 2:13
  • @MayorMonty yep. – acrolith Aug 6 '16 at 2:20
  • 2
    Can we output array of strings instead? – Leaky Nun Aug 6 '16 at 5:10
  • @LeakyNun no 15 chars – acrolith Aug 6 '16 at 16:58
  • May we print with a trailing newline? – Giuseppe Oct 4 '17 at 15:53

50 Answers 50

Vim, 59, 57, 48 bytes/keystrokes

$:let @q=float2nr(sqrt(col('.')))."|li<C-v><cr><C-v><esc>@q"<cr>@q

Since V is backwards compatible, you can Try it online!

I randomly received an upvote on this answer, so I looked over it again. My vim-golfing skills have greatly increased over the last 7 months, so I saw that this answer was very poorly golfed. This one is much better.

Brainfuck, 116 112 bytes


Try it online!

Safe in flavours of BF that does not mask the cells with 256, does not support null bytes.

Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.


The program is divided into 3 stages:

Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

Stage 1

In this stage, we put all the characters onto the tape, while keeping count of the number of characters.

This is the tape for the input abcdefghi after this tape:

000 009 000 000 095 096 097 098 099 100 101 102 103

The 009 is the count.

For each character, we move the the first zero on the left [<] and then add one to the count <<+>>>, and then move to the rightmost zero [>] to get ready for the next character.

Stage 2

This stage does the square root of the length stored in the second cell.

It keeps subtracting by 1, 3, 5, 7, ... until the number reaches zero, while keeping check of the number of iterations.

It works because square numbers can be expressed as 1 + 3 + 5 + ....

Stage 3

Denote the square root of the length found above as n.

This stage outputs n characters at a time, and then output a newline, until the tape is cleared.

Python 2, 55 bytes

while s:print s[:n];s=s[n:]
up vote 9 down vote accepted

05AB1E, 5 bytes


Try it online!

D    duplicate a (implicit input)
g    length of a
t    square root of a
ô    push a split in pieces of b
«    join by newlines (implicit output)
  • 1
    Great answer. But how does it work? Could you please edit to add an explanation? – grooveplex Aug 6 '16 at 13:22
  • @grooveplex done. – acrolith Aug 6 '16 at 15:51
  • Very impressive! – Gryphon Jun 7 '17 at 17:44
  • 1
    It's weird to see old 05AB1E answers where » is newlines now. – Magic Octopus Urn Jun 13 '17 at 17:36

MATL, 6 bytes


Try it online!


t     % Take input implicitly. Push another copy
n     % Get number of elements of the copy
X^    % Take square root
e     % Reshape the input into that number of rows, in column-major order
      % (which means: down, then across)
!     % Transpose so that text reads horizontally. Implicitly display
  • square "toor"? :P – acrolith Aug 5 '16 at 22:48
  • @daHugLenny :-D. Corrected – Luis Mendo Aug 5 '16 at 22:48
  • 4
    @daHugLenny That's the inverse of the square root. ;-) – WBT Aug 6 '16 at 5:46

Jelly, 8 7 bytes


Saved a byte thanks to @Dennis.

Try it online.


sLƽ$j⁷  Input: string S
    $    Monadic chain
 L         Get the length of S
  ƽ       Take the integer square root of it, call it n
s        Split S into chunks of size n
     j⁷  Join using newline
  • 2
    œs and s do the same thing here. – Dennis Aug 5 '16 at 22:48
  • Why does ½ not work instead of ƽ? – Luis Mendo Aug 5 '16 at 22:48
  • @LuisMendo Because it returns a float. I'll patch s and œs so they cast to int. – Dennis Aug 5 '16 at 22:49
  • @Dennis long-awaited patch still waiting... – Erik the Outgolfer May 15 '17 at 10:51

JavaScript (ES7), 49 bytes


44 bytes in Firefox Nightly 43-46 only (** was introduced some time between Firefox Nightly 42 and 43 and g as a separate parameter was removed some time between Firefox Nightly 46 and 47):

  • In the first version why do you need the + in s.length*+.5 – Downgoat Aug 6 '16 at 1:54
  • I've never seen the *+ syntax before. Could someone please explain it? – MayorMonty Aug 6 '16 at 2:25
  • He probably means **. – Conor O'Brien Aug 6 '16 at 5:53
  • @MayorMonty Yeah it was a typo sorry. – Neil Aug 6 '16 at 9:37
  • @Downgoat It was a typo sorry. – Neil Aug 6 '16 at 9:38

J, 9 bytes


This is a monadic hook over the input string:

$~ ,~@%:@#

The right tine is a series of compositions:

,~ @ %: @ #

The left is a shaping verb, switched such that it works in the hook format.

Here are some intermediate results:

   # 'hiya'
   %:@# 'hiya'
   ,~@%:@# 'hiya'
2 2

In words:

   size =: #
   sqrt =: %:
   dup =: ,~
   on =: @
   shape =: $~
   block =: shape dup on sqrt on size
   block 'Hello, World! :)'
o, W
! :)
  • 1
    I like the fact that $~,~@ resembles some sort of emoticon but @ seems weird for an ear but & fits better, or $~,~& – miles Aug 6 '16 at 6:13
  • And I do suppose they are functionally equivalent. Well, mostly. One lets you hear better than the other ;) – Conor O'Brien Aug 6 '16 at 6:14
  • 1
    +1 for having your score be n². Mine is too :) – Digital Trauma Aug 6 '16 at 22:49
  • @DigitalTrauma fun! +1 likewise! – Conor O'Brien Aug 6 '16 at 22:51
  • $~2#%:@# is 8. The left part of a fork can be a constant. – FrownyFrog Oct 5 '17 at 11:22

C, 64 bytes

Call f() with the string to square.


Try it on ideone.

  • Can you make it work with implicit int argument instead of char*? – anatolyg Aug 7 '16 at 7:31
  • I don't think so. It needs to be dereferenced, so a numeric type won't work, and it can't be an int* since that would scale wrong when adding. – owacoder Aug 7 '16 at 12:27
  • Suggest s+=write(puts(""),s,m)); instead of s+=m)printf("%.*s\n",m,s); – ceilingcat Oct 11 at 6:16

Perl, 23 + 4 (-pF flags) = 27 bytes

-2 bytes thanks to @DomHastings
-1 bytes thanks to @DomHastings


Try it online!

Expanations : computes the square root (lets call it S for the explanation) of the size of the input (it will be always be an integer) (@F is used in scalar context, thus returning its size), then add a newline after each bloc of S characters.

  • Nice use of $@, ;) You can save a byte using y///c instead of length and I think you can use a literal new line as well. I was looking as trying to do something with setting $, and matching, but I think this is much shorter! – Dom Hastings Aug 5 '16 at 22:52
  • 1
    @DomHastings Yea, I thought you'd like the $@! Thanks for the y///c, I tend to forget that it exists. – Dada Aug 5 '16 at 23:21
  • 1
    @DomHastings managed to save 1 byte by using $= instead of $@, which allows to not use -l flag. – Dada Aug 7 '16 at 12:26
  • Good going! Good to use the magic variables for genuine reasons too! – Dom Hastings Aug 7 '16 at 14:00
  • Hey, hope you're doing alright! This got bumped to homepage and I noticed another optimisation for -1: 23 bytes code + 4 for -pF – Dom Hastings Oct 5 '17 at 15:16

zsh, 36 bytes

fold -`sed s/.$//<<<$[$#1**.5]`<<<$1

Takes input as a command line argument, outputs to STDOUT.

                      $#1             get the length of the input string
                    $[   **.5]        take it to the .5 power (sqrt)
                 <<<                  and pass the result to
       sed s/.$//                     sed, which removes the last character
                                      this is because sqrt(9) is 3. instead of 3
     -`                       `       give the result as a command line flag to
fold                                  the fold util, which wraps at nth column
                               <<<$1  pass the input as input to fold

05AB1E, 8 6 bytes

Thanks to @quartata for letting me know about the square-root function


Try it online!


D     Implicit input. Duplicate
g     Number of elements
t     Square root
ô     Split into chunks of that length
¶     Push newline character
ý     Join list by newlines. Implicit display
  • Very nice! Also, « is short for joining on newlines :). – Adnan Aug 5 '16 at 23:13
  • 1
    @Adnan Thanks! Now I have outgolfed myself :-D – Luis Mendo Aug 5 '16 at 23:21
  • I have rolled back to my 6-byte version because there was a previous answer with « – Luis Mendo Aug 5 '16 at 23:52
  • 1
    Oh, that's too bad :( – Adnan Aug 5 '16 at 23:56
  • Does anyone else feel like those languages specifically created for code golf are kinda ruining the appeal of this whole thing? – René Roth Aug 7 '16 at 16:15

Python, 94 75 71 65 63 bytes

import re;lambda r:"\n".join(re.findall("."*int(len(r)**.5),r))

Old version:

lambda r:"\n".join(map("".join,zip(*[iter(r)]*int(len(r)**.5))))
  • Note that you can use input() by default to receive input in quotes, unless you want to specifically remove that option. – xnor Aug 5 '16 at 22:34
  • @xnor Oh wow, a few days ago I was wondering if I could use quotes on input... – acrolith Aug 5 '16 at 22:42
  • Wouldn't it be shorter to use a lambda? – Leaky Nun Aug 6 '16 at 4:58
  • @LeakyNun true... – acrolith Aug 6 '16 at 15:54

CJam, 8 bytes


Try it online!


l     e# Read line from input
_,    e# Duplicate. Get length 
mQ    e# Integer square root
/     e# Split into pieces of that size
N*    e# Join by newline. Implicitly display

Pyth, 8 bytes


Try it online

How it works

    lQ     length of input
   @  2    square root
  s        floor
 c     Q   chop input into that many equal pieces
j          join on newline

Dyalog APL, 10 bytes



         ≢   length of the argument   
     .5*⍨    square root 
   2⍴        reshape that to a length-2 vector
⊢⍴⍨          reshape the input by that vector


      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world'
      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world! Hello'
d! H
      (⊢⍴⍨2⍴.5*⍨≢)'Lorem ipsum dolor sit amt'
m dol
or si
t amt
      (⊢⍴⍨2⍴.5*⍨≢) 'H'

Cheddar, 27 bytes (non-competing)


I added the .chunk function a while ago but I removed it in the transition to the new stdlib format and forgot to re-add it. Cheddar has a dedicated sqrt operator but **.5 is shorter

Try it online!


s ->              // Function with argument s
    s.chunk(      // Chunk it into pieces of size...
      s.len ** .5 // Square root of length.
    ).vfuse       // Vertical-fuse. Join on newlines

Brainfuck, 83 bytes


Try it online!

This uses the same idea as Leaky Nun's answer. He asked for help golfing it in chat, then suggested that I add this as a new answer. (Actually what I wrote in chat was an 84-byte solution very similar to this.)

For the sake of comparison, an extra > is needed at the beginning for brainfuck implementations that don't allow negative memory addresses.

As expected, this finds the length of the input, then takes the square root, then prints the lines accordingly. It takes advantage of perfect squares being partial sums of 1 + 3 + 5 ....

PHP, 51 bytes


Perl 6, 38 bytes

$_=get;.put for .comb: .chars.sqrt.Int


$_ = get;          # get a single line of input

$_.put             # print with trailing newline

for                # every one of the following:

$_.comb:           # the input split into

$_.chars.sqrt.Int  # chunks of the appropriate size

Ruby, 40 33 + 1 (p flag) = 34 bytes

Run the code with ruby -pe followed by the code enclosed in single quotes.

-7 bytes from @Jordan.


Cheddar, 57 bytes


Since variables are broken, I would have to pass in variables through lambda application.

Also, it turns out that even if variables worked, it would still be shorter to use lambda application.


cheddar> (n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5))("abcd")

Pyke, 5 bytes


Try it here!

PowerShell, 58 61 bytes


Bash + GNU utilities, 25

fold -`dc -e${#1}vp`<<<$1

Not so different to @Doorknob's answer, but dc is a shorter way to get the square root.

𝔼𝕊𝕄𝕚𝕟, 11 chars / 14 bytes

ѨĊ(ï,√ ïꝈ⸩Ė⬮

Try it here (ES6 browsers only).

Generated using this code (run in the interpreter's browser console):

c.value=`Ѩ${alias(_,'chunk')}(ï,√ ïꝈ⸩${alias(Array.prototype,'mjoin')}⬮`

Brain-Flak, 110 96 bytes


Try it online!

Second solution, 96 bytes


Try it online!


Here I explain the first solution, both are the same length but I like the first one because it is cooler and employs some nice tricks.

The most important part of the code is a modified square root function I wrote some time ago. The original version was


And this works, but we actually want two copies of the negative square root. Why? We need two copies because we are looping through the string at two levels, one to make the lines and one to count the number of lines. We want it to be negative because looping with negatives is cheaper.

To make this negative we move around the [...] so it looks like this


To make two copies we change when pops occur


Now that we have that bit we can put it together with a stack height to get the first chunk of code we need.


We move to the offstack because our square root function needs two free zeros for computation, and because it makes stuff a little bit cheaper int he future in terms of stack switching.

Now we construct the main loop


This is pretty straight forward, we loop n times each time moving n items and capping it with a new line (ASCII 10).

Once the loop is done we need to reverse the order of our output so we just tack on a standard reverse construct.


Convex, 7 bytes


Try it online!

Fun fact:

_,mQ/\* also works on TIO due to how it works.

How have I forgotten to make a 1-char square root op?

Matlab, 28 bytes


reshape puts output in columns first, so we have to transpose the whole thing to get the desired output.

Java 1.7, 110 bytes

void f(String s){for(int i=-1,k=(int)Math.sqrt(s.length());++i<k;)System.out.println(s.substring(i*k,i*k+k));}

Try it! (Ideone)

I tried another approach with a function returning the result as a string, but just having to declare the string and the return statement is already more expensive (byte-count-wise) than the print statement.

Gotta love Java's verbosity... :)

  • Nice answer +1. You can golf it by 1 byte by using i=0, i<k and s.substring(i*k,i++*k+k) instead of i=-1, ++i<k, s.substring(i*k,i*k+k). Also, usually we use just Java 7 instead of Java 1.7, but it's good that you've added it, a lot of people forget to do so. – Kevin Cruijssen Sep 7 '16 at 8:58

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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