[Question]
  [
In this challenge you will be given an alphabetic string as input. We will define the "anti-string" of a given input to be the string with the case of all the letters inverted. For example
```
AaBbbUy -> aAbBBuY
```
You should write a program that takes a string as input and searches for the longest contiguous substring whose anti-string is also a contiguous substring. The two substrings should not overlap.
As an example if you were given the string
```
f**AbbA**cGf**aBBa**gF
```
The bolded portions would be the longest string anti-string pair.
Your program should, once it has found the pair, collapse them into a single character each. It should do this by removing all but the first character of each substring. For example the string above
```
f**AbbA**cGf**aBBa**gF
```
would become 
```
f**A**cGf**a**gF
```
Your program should then repeat the process until the longest string anti-string pair is a single character or shorter.
For example working with the same string the new longest pair after the collapse is
```
fAc**Gf**a**gF**
```
So we collapse the string again
```
fAc**G**a**g**
```
Now the string cannot be collapsed further so we should output it.
In the case of a tie between candidate pairs (example `AvaVA`) you may make either reduction (`AaA` or `AvV`, but not `Aa`).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Test Cases
```
fAbbAcGfaBBagF  ->  fAcGag
AvaVA ->  AaA / AvV
QQQQQQQ -> QQQQQQQ
fAbbAcQQQQaBBacqqqqA -> fAbcQBcq
gaq -> gaq
fAbbAcGfaBBagFaBBa -> fcGaBBag
```
## Motivations
While this problem may seem arbitrary it is actually a problem I encountered while making code to process fundamental polygons. This process can be used to reduce a fundamental polygon to a smaller **n**-gon. After I tried it I thought it would make a nice little golf.
  
[Answer]
# Perl, ~~64~~ 61 bytes
Includes `+1` for `p`
```
perl -pE 's/(.\K.{$%})(.*)(?=(.))(??{$1^$"x$%.$"})/$2$3/ while$%=--pos' <<< fAbbAcGfaBBagFaBBa
```
[Answer]
# JavaScript (ES6), 200 bytes
Uses arrays of characters for I/O.
```
f=a=>(m=M=C=>a.map((_,i)=>a.map((_,j)=>C(i,j-i+1))))(I=>M((i,j)=>a.slice(i,i+j).some((n,k)=>n[c='charCodeAt']()^(a[I+k]||'')[c]()^32)|I+j>i|j<m||(x=[i,I],m=j)))&&m-->1?f(a,x.map(p=>a.splice(p+1,m))):a
```
[Try it online!](https://tio.run/##hVC9bsIwEN55ikzkrDhGtFtVpzJIrTIwsLBEKRxuktrgJBCEGPLuqZ0y0Cq0N5x0d9@fTuMZG3lU9Sksq4@s63KOPALDF3zOI2QGa4A1VeRm0HaYg6I6VMGU2IKYRwtwmx7W7JXM7KQCTVhTmQygpDt7KhPJffmJx7m1Eic/BfIOmMTBLm1b3yeJdJvHB9LGgY5Uq59N28KFJ4rGKTVcW6/x2IRhNH3JAemlT1T3nnVvWgdTaizqCTtZlU21z9i@KiCHhDHm52K7FfItx9kMi1c/JUxXqtxsiHetycTLLQCL0QBbnHElBkjeDVug8Gw/r4YElt91X8IKXDGju@nd1eWXB1s/4/Tpt3I5k4chfoGHv9L3fIsZ/fs4138pOWv7N3fuvgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 119 bytes
```
.+
$&¶$&
T`Ll`lL`.*¶
/(.).*¶.*\1/^&0A`
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'
N$`
$.&
}0G`
```
[Try it online!](https://tio.run/##VY3NCoJAFIX39zlu0zjRqP2tShkXuZEgiFYSd5SUQAIj3PVaPoAvZnds1VkcPs45l/u6vx9PG44zmdKoF4Bi6FHAhbKGmoy0GnrwpfYcaJWH/k0EhmDoRdYhyXh/4FJ5kn0Ct5NxJLlZhhEnnDNuommllZevALe4wzXO4YQEqAV8An4@VqYoTJlWNklsfQTT2auB80/wKx26umxZBmrbwv@V8y8 "Retina – Try It Online") Link includes test cases. Explanation:
```
.+
$&¶$&
T`Ll`lL`.*¶
```
Duplicate the input and flip the case of the first copy.
```
/(.).*¶.*\1/^&0A`
```
If there are no anti-strings at all then delete the flipped duplicate.
```
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'
```
List all the possible collapsed anti-strings.
```
N$`
$.&
}0G`
```
Sort them in order of length, take the shortest (i.e. longest anti-string), and repeat until all the anti-strings have been collapsed.
[Answer]
# [Python 3](https://docs.python.org/3/), 189 181 bytes
Credit to Jonathan Frech for making it pure one-liner.
```
f=lambda s,x=set():any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()])and f(x.pop())or s
```
[Try it online!](https://tio.run/##dVA9b4MwEN3zK7zZFi4q6obEYIZmzpIFeTgMpiBiPgxt8uupDRZKUXrD6e69u3tP1z@mr05/LItKWrjlBSDD7okpJ0Jj0A8yo1ojkzVBHQvQBbmHUBTEZHETRCLwRDiWfQuyJDObs3fBIkq7EUVU2Vy7AyPoqiRtqYmhLGJvG9UcqRV1ipk9bBVqEZof6CWYklBBrT5S1kHf9WRVMEs/1noiimDF85zLs4I0heoTU4ZegChJkAXlGSpMT/su/4Yr9yu@ds4yzIFjhix2xeJp/rKF39i79frenQ7WHOp8yMEG/2PwSHmbubykcni@VMHgF9dqnVur0z9/cPnlLzZiE7LvcBimyy8 "Python 3 – Try It Online")
My own version, now obsolete (189 bytes):
```
x=set()
def f(s):
 while any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()]):s=x.pop()
 return s
```
[Try it online!](https://tio.run/##dVCxjoMwDN35imxJBIcO3YbEEIbr3KULYjAhoSAUIIEr/XouAYR6qOfBst@zn5/cP8d7p76WZU6MGAn1SiGRJIbGHnrc61YgUE8yoVohkzV@HeegSjKHUJbEZHHjR7m/E6EWfQtckCmYss88iCjtNIqotLl2AhpUJUgrlJUPouBjo5oztaLuYmaF7YU6D80Deg5GEJrT2CRz2He99Yq0GCdtnS29rtVIJMGSFQXjFwlpCtU3pgF6A6IkQRbkF6gw9Y5d9gM3tq/stfOWYQYMB8hiN5y/zF@32DeOblU/Ou9kzaHOBx9ssD8Gz9Rus@DXlA@vShUM@@JarXNr5f3zB5ff/mIjtkP2HQ7DdPkF "Python 3 – Try It Online")
`any()` to break out nested loops early, and `set()` for mutable global object usable in the comprehension. The rest is just the straightforward implementation of the requirements using `str.swapcase`.
# [Python 2](https://docs.python.org/2/), 160 bytes
```
def f(s):
 for i in range(len(s),1,-1):
	for j in range(len(s)):
	 u=s[j:j+i].swapcase()
	 if u in s[j+i:]:return f(s[:j+1]+s[j+i:].replace(u,u[0],1))
 return s
```
[Try it online!](https://tio.run/##dVA9b4MwEJ3Lr7jNtnCj0hGJwQzJnCULYjCuTY0iBwxulF9PbbBQilIP1t37uHu6/jF938znPH9JBQqPJE9A3Sxo0AYsN63EV2k8TjP6nnn2LbDdng0EuGKsurxLdX0Y77wXfJSYeFwrcMHg2VTndW7l5KwJ2yqvzuo0Egcr@ysXEjvqqo@aZoQkEMXj3FttJqwwUqxpmDgpXpa8PSJC4QUIRQEeFCfeIpJsXvbDLyxaYh2SVYhxhih47ILqJ/15fdGxdcv0rUt20QIacojBP/Yn4J6KMRtxLsXwPKnlQzQu1aJbquSfO4T/5S1WYl3kzxEwROZf "Python 2 – Try It Online")
Turns out that regular nested for loop with early breaking through `return` is way shorter than the "clever" trick with `any`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~240~~ ~~238~~ ~~227~~ ~~225~~ ~~222~~ 216 bytes
* Saved two bytes; removed a stray variable definition.
* Saved ~~eleven~~ thirteen bytes; golfed `b|=S[p+m]!=S[q+m]+32-(S[q+m]>90)*64` to `b|=abs(S[p+m]-S[q+m])-32` to `b|=32-S[p+m]+S[q+m]&63`.
* Saved three bytes; golfed `for(...;...;p++)S[p+1]=S[p+L];` to `for(...;...;S[++p]=S[p+L]);`.
* Saved six bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
p,P,q,Q,l,L,b,m;f(char*S){for(p=0;S[p];p++)for(l=0;S[l+++p];)for(q=0;b=S[q+~-l];!b&p+l<=q&l>L?L=l,P=p,Q=q:0,q++)for(b=0,m=l;m--;)b|=32-S[p+m]+S[q+m]&63;for(;b-2;)for(p=b++?-~Q-L:P;S[p];S[++p]=S[L+p]);~-L?L=0,f(S):0;}
```
[Try it online!](https://tio.run/##ZZA/b4MwEMXn9lO0DBGubQklUoe4bmSSwMIQhNQFMdiWoJWgtdM/S5p8deojBoZ68Envfs/vzpo2Wve9IQdiSU5akhFFOlaH@lUeHwp0qj@OoeERK0pTMYMxAqEdhBZj7MRBsU5RvCgtvtC2YvdqYXD7xO2ifc42GW/JgRuSc7uOiPWPKB6Rjreso5Qh9ctXS@pCcFdheKarFo8rBhxTdHkNMVxhvKGXnGbrw3WiooQZXHDmCmIXCmkRqcMCrSN27jv59h6i0@0N7HMnyooHtVBK6LSWcSybJHC7CsTM99fnVB2iU9kEiHlfDD7xI18E4LHHxhoIKWZ2C2x@PUBvPTXWqTc5dvNU0IC5tHVnCNt5226eTek81nb278HfSAv43mNjHfSJTP7vDzcYE29Iphz3BUDM7hTcUkohhLvBlHp4rIEcOs5x7v8A "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 180 bytes
```
def f(s):
 L=len(s)
 for x,y in[(i,i+j)for j in range(L,1,-1)for i in range(L-j)]:
	t=s[x:y];T=t.swapcase()
	if T in s[y:]:return f(s.replace(t,t[0],1).replace(T,T[0],1))
 return s
```
[Try it online!](https://tio.run/##TZBNb8MgDIbP5Vf4BmhOtezIlEnpYbv0MinaBeVAM8iIKpoC25pfn8XNvnywXj@82Jhxym@ncDfPr9aBE0kqBvvqaMMiGbhThAtO4IMWHv3NIIkMSw3RhN6KPZZYlFfq/9FikK1im1wlfVFTe99UeZs@zdiZZIVkG@@gIXvSk2pVtPk9Bpq@jXY8ms6KjFnftljKX9Jgs5LlWd8X0kxzEzXS3NWHQ909ObPbmf6RI/D6w7zUJJ7XILm6qCJfd17iaunN@e/4pwllTnuM0YcMCXnxwJE@ic1f "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 30 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
î☼fúΩ§☺æ╒ºê@Ñ▀'╫Iqa{d]∟Sa5♦⌂─╚
```
[Run and debug it](https://staxlang.xyz/#c=%C3%AE%E2%98%BCf%C3%BA%CE%A9%C2%A7%E2%98%BA%C3%A6%E2%95%92%C2%BA%C3%AA%40%C3%91%E2%96%80%27%E2%95%ABIqa%7Bd%5D%E2%88%9FSa5%E2%99%A6%E2%8C%82%E2%94%80%E2%95%9A&i=fAbbAcGfaBBagF%0AAvaVA%0AQQQQQQQ%0AfAbbAcQQQQaBBacqqqqAgaq%0AfAbbAcGfaBBagFaBBa&a=1&m=2)
The corresponding ascii representation of the same program is this.
```
c%Dc:e{%orF..*:{_{32|^mY++_h.$1yh++R
```
It uses a regex approach. It repeatedly regex string replacement. It builds these from each contiguous substring of the current value. For instance for the input `fAbbAcGfaBBagF`, one of the substrings is `AbbA`, in which case the regex `AbbA(.*)aBBa` will be replaced with `A$1a`.
```
c                                       get number of characters
 %D                                     repeat rest of program that many times
   c:e                                  get all substrings
      {%or                              order substrings longest to shortest
          F                             for each substring, execute the rest
           ..*:{                        build the string "(.*)"
                _{32|^m                 current substring with case inverted
                       Y                save the inverted case in register y
                        ++              concatenate search regex together
                                            e.g. "aBc(.*)AbC"
                          _h            first character of substring
                            .$1         "$1"
                               yh       first character of inverted case
                                 ++     concatenate replacement regex together
                                            e.g. "a$1A"
                                   R    do regex replacement
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 148 bytes
```
#//.s_:>MinimalBy[StringReplaceList[s,a:(p_~~__)~~x___~~b:(q_~~__)/;(32==##&@@Abs[(t=ToCharacterCode)@a-t@b]):>p<>x<>q]/.{}->{s},StringLength][[1]]&
```
[Try it online!](https://tio.run/##RY1fS4RAFMW/ymUEUdAdqjdbB3WhXjZoK3oZhuFqow6srn@m2BD96qZJdB4u557z494KTakqNDrDOYcQZovSXS8D9qRrXeE5@eavptN18aKaM2bqqHvDew8Dp5HTJKU7TVcpF5sGTrsl9N65uw1Dy7KjKE577pjw7XIoscPMqO5w@VBuhL6JUuEGrNmz6561gu6G0WdDP3rbu6OqC1MKzm@EsOfnJTLc8oCAz4B4kHNLCLCBRjCQPE7TOHvMMUmweFhaEn/he7ya06bVbtS6rVzWLvpFCmz/678j6yQjUAqnT63M/AM "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 33 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4CDxysXUoz1yWCsiKC4qKSIrWGNeSCDIzitZK1jOY15I&input=ImZBYmJBY0dmYUJCYWdGIg)
```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H     :Implicit input of string U
à                                     :Combinations
  ñ                                   :Sort by
   Ê                                  :  Length
    Å                                 :Remove first element (the empty string)
     Ô                                :Reverse
      £                               :Map each X
       =                              :  Reassign to U
        r                             :  Global replacement
         X+"(.*)"+                    :  Append "(.*)" to X and then append
                  Xc                  :    Charcodes of X
                    ^H                :    XORed with 32
                      È               :  Pass each match X, with captured group Y, through the following function
                       Î+Y+           :    Append Y to the first character of X and then append
                           XÎc^H      :      The charcode of the first character of X XORed with 32
```
]