Oh, No!
the sentences are out of balance.
Quick! balance them.

A word is defined as follows:

A sequence of letters [A-Za-z] separated by any non-letter character ([0-9] ~+- etc.)

A word is BaLanCeD if its capitalization is the same forwards as it is backwards.

Given a sentence with words, balance each word by capitalizing a letter on the right-hand side for each uppercase letter on the left-hand side, and the other way around. Do not make uppercase letters lowercase.


  • For each letter n chars from the beginning of a word, it and the letter n chars from the end of the word should both be made uppercase if either of them is upper case.
  • All input will be printable ASCII (codepoints 32 to 126 ~).

No need to balance if:

  • The capital is in the middle of a term (word) (equal amount of letters on each side)
  • No capitals are present in the term


eeeeE → EeeeE  
eEeee → eEeEe
eeEee → eeEee
Eeee. → EeeE.

TesT CaSeS:

It was the first new century. →
IT was the first new century.

IiIIiiIIiiiI Ii iI iiiI iiii iIi. →

I sueD the airport for misplacing my Luggage. – I lost my Case. →
I SueD the airport for misplacing my LuggagE. – I lost my CasE.

The Policemen  CraCked THE CaSE of the lost cocaIne. →
ThE PolicemeN  CraCkeD THE CASE of the lost coCaIne.


If(!1){ /\hElloBinOLIngo}elsE{ print( 'bOn aPPetit')} →
IF(!1){ /\hElLOBinOLInGo}ElsE{ print( 'bOn aPPeTIt')}

xK/TH"E7k['VyO%t>2`&{B9X.8^$GWc=!+@ 3Us}]JFM)jbuI,-:alPw*Qvpq5zi\Z(_n1dC~?<;fDAm0SR|eYg6#rN4Lho →
XK/TH"E7k['VyO%t>2`&{B9X.8^$GWC=!+@ 3US}]JFM)JbuI,-:aLPw*QvpQ5zi\Z(_n1DC~?<;fDAm0SR|eYg6#RN4LhO

Foo_bar →

(the " →" will not be included in the input)

This is codegolf, so attempt to achieve least amount of bytes

  • 1
    \$\begingroup\$ Suggested test case: Foo_bar. To make sure that words are not matched with \w+. \$\endgroup\$
    – Arnauld
    Feb 24, 2021 at 9:51
  • 5
    \$\begingroup\$ Suggest just using @Xcali's description as I didn't have a clue what this was all about until I read that. \$\endgroup\$
    – Noodle9
    Feb 24, 2021 at 10:49
  • 5
    \$\begingroup\$ The specifications of this challenge are very confusing. It reads as if there has been a paragraph cut out of the challenge. \$\endgroup\$
    – Wheat Wizard
    Feb 24, 2021 at 11:57
  • \$\begingroup\$ what's a "term" \$\endgroup\$
    – ASCII-only
    Feb 26, 2021 at 21:41
  • 1
    \$\begingroup\$ might wanna clarify that \$\endgroup\$
    – ASCII-only
    Feb 26, 2021 at 21:51

22 Answers 22


JavaScript (Node.js),  76  72 bytes

Saved 2 bytes thanks to @tsh


Try it online!


s =>                     // s = input string
s.replace(               // replace in s:
  /[a-z]+/gi,            //   match all words in a case-insensitive way
  w =>                   //   for each word w:
    Buffer(w)            //     turn it into a Buffer
    .map((c, i, a) =>    //     for each character c at position i in this array a[]:
      c &=               //       bitwise AND of c with:
        a[w.length + ~i] //         the counterpart character taken from the end of
                         //         the word
        | 95             //         OR 0b1011111
                         ///        (all letter bits except the lowercase bit)
    )                    //     end of map()
                         //     implicit coercion of the Buffer to a string
)                        // end of replace()
  • 3
    \$\begingroup\$ c&95^c&a[w.length+~i]&32->c&(a[w.length+~i]|~32) \$\endgroup\$
    – tsh
    Feb 24, 2021 at 10:32

Jelly, 18 bytes


A full program that takes a string argument and prints the result.

Try it online!


=ŒsŒgṁ@µŒu=ŒuṚTƲ¦) - Main Link: list of characters (S)
 Œs                - swap-case (only affects alphabetic characters)
=                  - (S) equals (that); vectorises
   Œg              - group runs of equal elements
     ṁ@            - (S) mould-like (that) -> list of "words"
                       (any single non-alphabetic character is now a word)
       µ         ) - for each (word in that):
                ¦  -   sparse application...
               Ʋ   -   ...to indices: last four links as a monad:
           Œu      -       upper-case (word)
          =        -       (word) equals (that); vectorises
             Ṛ     -       reverse
              T    -       truthy indices
        Œu         -   ...action: upper-case (the character at the index)
                   - implicit, smashing print (just prints the characters in the list of lists)

Seems a bit long to me:

  • The partitioning atoms (œṖ, œṗ, œP, and œp) don't seem to help much here even though it seems like they should.
  • Perhaps there is a way to shorten code by zipping (") a dyadic function with the reverse of each (U)?

Perl 5 -p, 60 bytes


Try it online!

  • \$\begingroup\$ 32 bytes Try it online! \$\endgroup\$ Feb 25, 2021 at 10:43
  • 1
    \$\begingroup\$ You should post that as a new answer. It's a lot shorter and you should get credit. Plus, I don't even understand how it works. \$\endgroup\$
    – Xcali
    Feb 25, 2021 at 18:01

C (gcc), 132 \$\cdots\$ 115 114 bytes

Saved 3 11 bytes thanks to AZTECCO!!!


Try it online!

Modifies the input string to have in-word balanced capitalisation.


f(s,e)char*s,*e;                           // function taking a string   
{                                          // parameter s and also declares   
                                           // e as a string pointer
  for(;!isalpha(*s);++s);                  // loop until s pointes to the   
                                           // beginning of the next word   
  for(e=s;isalpha(*++e););                 // loop until e pointes to one  
                                           // past the end of that word   
  for(                                     // loop over this word   
      *e&&f(e);                            // while e points to one past
                                           // the current word     
                                           // recursively handle the next 
                                           // word if we're not at the end    
               s<e;                        // loop while s is before e  
                   ++s)*--e                // bump s and e towards the middle   
                   ++s)                    // bump s forwards at the end of  
                                           // each loop  
                       *--e                // bump e backwards at the   
                                           // beginning of each loop 
                       *--e&*s&32||        // if both characters aren't  
                                   (       // both lower case then   
                                    *s&=95 // make the first character upper             
                                   ,       // case regardless of its case    
                                    *e&=95 // and also make the second    
                                           // character upper case    
                                   );      // regardless of its case   
}                                          //       
  • 1
    \$\begingroup\$ Nice! SuggestTry it online! \$\endgroup\$
    Feb 25, 2021 at 8:42
  • 1
    \$\begingroup\$ @AZTECCO Sweet, just cache the end of word and leave out synching at the start - thanks! :))) \$\endgroup\$
    – Noodle9
    Feb 25, 2021 at 9:54
  • 2
    \$\begingroup\$ Wait.. You can get rid of b by placing function call before last loop! Try it online! \$\endgroup\$
    Feb 25, 2021 at 10:54
  • 2
    \$\begingroup\$ @AZTECCO Oh, that's diabolical - thanks! :D \$\endgroup\$
    – Noodle9
    Feb 25, 2021 at 11:07

Husk, 16 13 bytes


Try it online!

            ġo¬√    # first ġroup the input into sublists (words) according to whether the elements are/aren't letters
ṁ                   # now map across this list of words and concatenate the results into a string, with the function
 Sz        ↔        # zip together each word and its reverse using
   μ      )         # 2-argument lambda function:
    ?  D⁰           # if arg 1 is uppercase
     a   ²          # return uppercase of arg 2
      I             # otherwise return arg 2 unchanged

Python 3, 236 230 217 bytes

My first answer in Code Golf!

Edit: -6 bytes thanks to @movatica

-6 bytes thanks to @Danis

-7 bytes thanks to @Alex bries

for j in range(len(s)):
 if p<'A'or'a'<p<'Z'or p>'z':u=[c<'a'for c in s[i:j]];b=[x|y for(x,y)in zip(u,u[::-1])];o+=''.join([c,c.upper()][x]for(c,x)in zip(s[i:j],b))+p;i=j+1

Try it online!

Commented code (original):

import re

...import the regex module to find non letter characters


...take the imput from the console, and append a non letter character to complete the last iteration in the loop


...initialize the output string


...initialize the index to find the start of each new identified word

for j in range(len(s)):

...loop on the characters of the input

 if re.match('[^A-Za-z]',s[j]):

...identify a non letter character that separates words

u=[ord(c)<97for c in s[i:j]];

...list of boolean values corresponding to the letters in the word: True if uppercase

b=[x|y for(x,y)in zip(u,u[::-1])];

...reverse the list of boolean values, and apply or elementwise to obtain the symmetric list of uppercase characters

o+=''.join([[c,c.upper()][x]for(c,x)in zip(s[i:j],b)])+s[j];

...builds the output string: convert to uppercase according to the symmetric list built before; add the non letter character


...update the starting index of the next word.


...prints the output balanced string (discarding the added last character)!

  • 1
    \$\begingroup\$ Welcome to Code Golf! Nice first answer! \$\endgroup\$ Feb 25, 2021 at 18:17
  • 2
    \$\begingroup\$ Welcome, fellow Python golfer! :) I'm sorry to outgolf you on this one, but you got very similar concepts and can easily grab some techniques to golf them further! Here are two hints: use o+=.. instead of o=o+.. for one byte less and [c,c.upper()][x] instead of c.upper()if x else c for a 5 byte improvement. \$\endgroup\$
    – movatica
    Feb 26, 2021 at 16:38
  • 1
    \$\begingroup\$ @movatica I know, i'm not a professional golfer, tried just for fun! :) Thanks for your tips! Thank you all! \$\endgroup\$
    – SevC_10
    Feb 26, 2021 at 16:51
  • 1
    \$\begingroup\$ "".join([...]) --> "".join(...), ord(c)<97 --> c<"a" \$\endgroup\$
    – Danis
    Feb 27, 2021 at 19:40
  • 2
    \$\begingroup\$ Nice answer, i learnt a few tings from it too. You can also remove the re module by replacing the match with: z=s[j] #a line break if z<"A"or z>"z"or "Z"<z<"a": \$\endgroup\$
    – Alex bries
    Feb 28, 2021 at 22:46

Ruby, 73 72 bytes


Try it online!


Retina 0.8.2, 62 bytes


Try it online! Explanation:


Count the number of letters following the match.


Skip back to the beginning of the word, and then...


... match the same number of characters, ...


... followed by an uppercase letter.


Uppercase matching letters.


Stax, 19 16 bytes


Run and debug it

Replaces each match of [A-Za-z]+ using the ruleset.

-3, borrowing the untruth idea from Jonathan Allan's answer.


V^{c{96<mr:1{]^}&}R implicit input of string
V^                  regex: "[A-Za-z]+"
  {c{96<mr:1{]^}&}R replace each occurrence with the following regex:
   c                copy the match
    {96<m           boolean array for uppercase letters
         r:1        reverse and take truthy indices
            {]^}&   uppercase the match at those indices

Red, 155 152 bytes

func[s][a: charset[#"A"-#"Z"#"a"-#"z"]parse s[any[change copy w some a(repeat
i d: length? w[if w/:i < #"["[n: d - i + 1 w/:n: w/:n and 95]]w)| skip]]s]

Try it online!


Perl 5 (-p), 32 bytes


The trick, to uppercase, is to AND characters with the negation of space.

How it works

For each sequence of letters

bitwise NOT

bitwise AND with space character repeated (at least the size of the match, here majorant is the position after match @+)


bitwise negate

bitwise AND with matched.

Try it online!


Python 3, 153, 149, 148, 110 bytes

Using re.sub is even more elegant than re.finditer...

lambda s:re.sub('[a-zA-Z]+',lambda w:''.join([c,c.upper()][d<'a']for c,d in zip(w[0],w[0][::-1])),s)
import re

Try it online!


Julia, 76 bytes


Try it online!


Charcoal, 29 bytes


Try it online! Link is to verbose version of code. Link includes test suite. Explanation:


Loop over the input with a null terminator.


If the current character is a letter, ...


... push it to the predefined empty list, otherwise:


Loop over a copy of the saved letters, retrieving them in reverse order each time, and uppercasing the copy if the reverse order letter is uppercase.


Print the non-letter unless it's the null terminator.


Java, 320 Bytes


Try it online!


s->java.util.regex.Pattern.compile("[a-zA-Z]+").matcher(s)//match words
  .replaceAll(m->//replace each word, m is MatchResult, m.group() is current word
     java.util.stream.IntStream.range(0,m.group().length())//iterate over indexes of word
       //check if character at reflected index is uppercase
  Character.toUpperCase(m.group().charAt(i))//make uppercase
  :m.group().charAt(i)) //do not modify
   + "" //concatenate with empty string to force result to be a String
  ).collect(java.util.stream.Collectors.joining()))//collect as single String

J, 60 bytes


Try it online!

Well this is shockingly verbose for J. Surely I am missing some better alternatives, but this is what I have for now...


Java (JDK), 130 bytes

a->{for(int i=0,l=a.length,c,s,e;i<l;i++){for(s=i;i<l&&(c=a[i]&95)>64&c<91;i++);for(e=i;s<e;a[e]&=c)a[s]&=c=a[s++]^a[--e]^32|95;}}

Try it online!



AWK, 113 bytes 141 bytes

{for(b=1+split($0,l,"[ ]");--b;$b=e){a=split(toupper(m=l[b]),c,d=e=x);for(split(m,f,d);a;a--){if(f[++d]==c[d])f[a]=c[a];}for(;d;)e=f[d--]e}}1

Try it online!

The code got longer to address a bug related to whitespace parsing as noted by Dominic van Essen.

This isn't all that short, but AWK isn't well suited to this challenge (as far as I can tell) so I think it's worth posted anyway.

Here's how it works...

The first for loop processes each commandline argument in reverse order. First it has to break the arguments into words explicitly, since TIO doesn't provide a way to set RS and ORS variables easily.

b=1+split($0,l,"[ ]")

which sets variable b to the number of space delimited words found, and stores the array of words (some of which might be empty strings) in variable l. The 1+ is necessary to keep the code from skipping the last word.

then at the top of each loop,


the code decrements b. The words in the array are processed in reverse order to avoid having to use another variable.

The body of the loop consists of three statements, the first one is:


which does a couple of things.

  • converts the current argument l[b] to upper case
  • splits that word into a character array, assigns that to variable c
  • sets variables d and e to an empty string
  • set variable a to the number of characters in the argument
  • stores the untranslated value of the current argument in variable m

The second statement is another loop, checking character by character and translating to uppercase as needed. It does that by initializing the loop with:


which converts the current commandline argument to a character array, stored in variable f. At this point f has the original characters, and c has the same characters translated to uppercase.

The loop condition and "end of loop" action cause the code to iterate a times, which is the number of characters in the current argument.

The body of this second loop is single statement:


which translates the paired character to uppercase if the character we're checking is already uppercase. The loop decrements a and increments d each iterations, which keeps the pairing in sync.

The third statement in the body of the outer loop, is essentially a "join" operation concatenating the characters in the translated character array.


The only trick here is using the d variable as the iteration control, since it was incremented up to the length of the commandline argument in the previous loop. Also working backwards means we can use f[d--]e without having to use a space between them since the closing bracket separates the variables.

Then the "end of loop" action on the outer loop assigns the re-assembled string to the current commandline argument.


And all that's left to do is add a "truthy" test without any action to print everything.

  • 1
    \$\begingroup\$ This is really nice. Well done! I don't know why the TIO awk doesn't accept the standard -v RS=' ' and -v ORS=' ' command-line options, but using them on my local awk, one can sorten it to 104 bytes: {a=split(toupper($0),c,d=e=x);for(split($0,f,d);a;a--)if(f[++d]==c[d])f[a]=c[a];for(;d;)e=f[d--]e;$0=e}1 \$\endgroup\$ Feb 28, 2021 at 11:03
  • 1
    \$\begingroup\$ (there is an issue, though, that awk is splitting on whitespace/spaces, rather than on all non-letter characters as specified in the challenge...) \$\endgroup\$ Feb 28, 2021 at 11:05
  • 1
    \$\begingroup\$ (splitting issue can be resolved using a regex in GNU awk (gawk), which is also sadly not implemented on TIO: gawk -v RS='[^a-zA-Z]' -v ORS=' ' '{a=split(toupper($0),c,d=e=x);for(split($0,f,d);a;a--)if(f[++d]==c[d])f[a]=c[a];for(;d;)e=f[d--]e;$0=e}1'...) \$\endgroup\$ Feb 28, 2021 at 11:28
  • \$\begingroup\$ ugh... I see what you mean about the whitespace and how relying on the commandline arguments splitting is a problem. I'll try to come with something that works on TIO that doesn't get confused by multiple spaces in a row on the input. \$\endgroup\$
    – cnamejj
    Feb 28, 2021 at 19:22

05AB1E,  15  13 bytes

-1 thanks to Makonede! (Duplicate-TOS and then reverse-TOS has a one-byte built-in, Â.)
-1 thanks to Kevin Cruijssen! (Take a list of characters.)


Try it online!


.γa}εÂ.uÅÏu]˜ - (accepts a list of characters)
.γ }          - group by:
  a           -   is alphabetic?
    ε         - for each:
     Â        -   push a copy and then push a reversed copy
      .u      -   is upper-case? (vectorises)
        ÅÏ    -   apply at truthy indices (of that, to the forward copy):
          u   -     upper-case
           ]  - } } (close all loops)
            ~ - flatten

Japt, 30 bytes

òÈ+Y è"%L"
®íZmr"%a" ÔÏ?Xu:XÃc

Try it online!

I'm not happy with this, but I haven't actually been able to find something better. Inputs and outputs as an array of characters.


òÈ+Y è"%L"    
ò                      # Partition the input between pairs of characters where truthy:
 È+Y                   #  Join the two characters into a string
     è"%L"             #  Count how many are not in [A-Za-Z]
                       # Implicitly store as U

®íZmr"%a" ÔÏ?Xu:XÃc    #
®                      # For each word:
  Zmr"%a"              #  Replace lowercase letters with ""
          Ô            #  Reverse it
 í         Ï     Ã     #  Pair each with the original letter at that index
            ?          #  If the modified array has anything other than "":
             Xu        #   Replace the original letter with upper-case
               :X      #  Otherwise leave it unchanged
                  c    # Flatten all the words back into a single array of chars
  • \$\begingroup\$ i'm happy with it :p \$\endgroup\$
    – Alex bries
    Feb 28, 2021 at 21:34

PowerShell, 91 82 bytes

$args-replace'[a-z]+',{-join(&{($w="$_")|% t*y|%{[char]($w[--$i]-bor95-band$_)}})}

Try it online!


  • &{ creates a new context each contains $i=0
  • -bor is bitwise or, -band is bitwise and have inspired by the Arnauld's answer

Uiua SBCS, 19 bytes


Try it!

                  .  # duplicate input
                ⌵±   # letter mask
⍜⊜□⍚(          )     # under partition (map over words, leave rest intact)
              .      # duplicate word
           =1±       # uppercase mask
        ↥⇌.          # mirror it
     ⍜▽⌵             # capitalize letters given by mask

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.