Problem:


Score : 400 points

Problem Statement

We have a string s consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in s of his choice, including the beginning and end of s.

Snuke's objective is to turn s into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and  abcba are palindromes, while ab, abab and abcda are not.

Constraints

1 \leq |s| \leq 10^5

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn s into a palindrome.

Sample Input 3

a

Sample Output 3

0

s is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx



Sample input:
xabxa


Sample output:
2

Submission status: Runtime Error

Solution code:
s = list(input())
n = len(s)
x = s.count("x")
a = n-x
if a%2:
    count = 0
    for i in range(n):
        if s[i] != "x":
            count += 1
        if count == a-a//2:
            ind = i
            break
    count = 0
    l = ind-1
    r = ind+1
    c1 = a//2
    while c1 > 0:
        lc = 0
        while l >= 0 and s[l] == "x":
            l += 1
            lc += 1
        rc = 0
        while r < n and s[r] == "x":
            r += 1
            rc += 1
        if s[l] == s[r]:
            count += abs(lc-rc)
            l -= 1
            r += 1
        else:
            print(-1)
            exit()
        c1 -= 1
    count += abs(n-r-(l+1))
    print(count)
else:
    count = 0
    for i in range(n):
        if s[i] != "x":
            count += 1
        if count == a//2:
            l = i
        elif count == a//2+1:
            r = i
            break
    count = 0
    if s[l] != s[r]:
        print(-1)
        exit()
    c1 = a//2-1
    while c1 > 0:
        lc = 0
        while l >= 0 and s[l] == "x":
            l += 1
            lc += 1
        rc = 0
        while r < n and s[r] == "x":
            r += 1
            rc += 1
        if s[l] == s[r]:
            count += abs(lc-rc)
            l -= 1
            r += 1
        else:
            print(-1)
            exit()
        c1 -= 1
    count += abs(n-r-(l+1))
    print(count)

Submission status: Runtime Error

Solution code:
s = list(input())
n = len(s)
x = s.count("x")
a = n-x
if a%2:
    count = 0
    for i in range(n):
        if s[i] != "x":
            count += 1
        if count == a-a//2:
            ind = i
            break
    count = 0
    l = ind-1
    r = ind+1
    c1 = a//2
    while c1 > 0:
        lc = 0
        while l >= 0 and s[l] == "x":
            l += 1
            lc += 1
        rc = 0
        while r < n and s[r] == "x":
            r += 1
            rc += 1
        if s[l] == s[r]:
            count += abs(lc-rc)
            l -= 1
            r += 1
        else:
            print(-1)
            exit()
        c1 -= 1
    count += abs(n-r-(l+1))
    print(count)
else:
    count = 0
    for i in range(n):
        if s[i] != "x":
            count += 1
        if count == a//2:
            l = i
        elif count == a//2+1:
            r = i
            break
    count = 0
    c1 = a//2-1
    while c1 > 0:
        lc = 0
        while l >= 0 and s[l] == "x":
            l += 1
            lc += 1
        rc = 0
        while r < n and s[r] == "x":
            r += 1
            rc += 1
        if s[l] == s[r]:
            count += abs(lc-rc)
            l -= 1
            r += 1
        else:
            print(-1)
            exit()
        c1 -= 1
    count += abs(n-r-(l+1))
    print(count)

Submission status: Runtime Error

Solution code:
s = input()
num = len(s)
l, r = 0, num-1
ans = 0

while l != r:
    if s[l] == s[r]:
        l += 1
        r -= 1
    else:
        ans += 1
        if s[l] == 'x':
            l += 1
        elif s[r] == 'x':
            r -= 1
        else:
            print(-1)
            break
print(ans)

Submission status: Runtime Error

Solution code:
s = input()
num = len(s)
l, r = 0, num-1

for i in range(num//2):
    if s[l] == s[r]:
        l += 1
        r -= 1
    else:
        if s[l] == 'x' or s[r] == 'x':
            ans += 1
            l += 1
        else:
            print(-1)
            break
print(ans)

Submission status: Runtime Error

Solution code:
S = input()
snx = S.replace('x', '')
ls = len(S)
if ls == 1:
    print(0)
    exit(0)
l = 0
r = ls-1

ans = 0
while l < r:

    lxc = 0
    while S[l] == 'x':
        l += 1
        lxc += 1
    
    rxc = 0
    while S[r] == 'x':
        r -= 1
        rxc += 1

    ans += abs(lxc-rxc)

    if S[l] == S[r]:
        l += 1
        r -= 1
    else:
        print(-1)
        break
else:
    print(ans)

Submission status: Runtime Error

Solution code:
s=input()
t=s.replace('x','')
n=len(t)
if not(n==1 or t[:n//2]==t[(n+1)//2:][::-1]):
  print(-1)
  exit()
n=len(s)
r=n-1
l=0
ans=0
while r>l:
  nr,nl=r,l
  while s[r]=='x':r-=1
  while s[l]=='x':l+=1
  ans+=abs(nr-r-nl+l)
  while s[r]==s[l] and l<r:
    r-=1
    l+=1
print(ans)

Submission status: Runtime Error

Solution code:
s = list(input())
l, r = 0, len(s) - 1
ans = 0
while l != r:
    if s[l] == s[r]:
        l += 1
        r -= 1
    else:
        if s[l] == "x":
            l += 1
            ans += 1
        elif s[r] == "x":
            r -= 1
            ans += 1
        else:
            ans = -1
            break

print(ans)

Submission status: Runtime Error

Solution code:
def isPal(s):
    if s == s[::-1]:
        return True
    return False

s = list(input())
pal = ''
for ch in s:
    if ch != 'x':
        pal+=ch

if not isPal(pal):
    print(-1)
else:
    beg = s.index(pal[0])
    end = len(s)-1 - s[::-1].index(pal[-1])
    half = 0 if len(pal) == 1 else len(pal)//2 + 1
    cnt = 0
    for i in range(len(s)):
        if cnt == half:
            break
        if s[i] != 'x':
            cnt += 1
    print(abs(cnt-beg - (end-cnt)) + abs(beg - (len(s)-1-end)))

Submission status: Runtime Error

Solution code:
s=list(input())
s2=[]
for i in range(len(s)):
    if s[-i-1]!="x":
        num=i+1
        break
s3=["O"]*num
for i in range(len(s)):
    if s[i]!="x":
        s2.append(s[i])
        if i!=len(s)-1:
            if s[i+1]!="x":
                s3.append("O")
    else:
        s3.append("x")
num=0
for i in range(len(s2)//2):
    if s2[i]!=s2[-1-i]:
        num=1
        break
if num==1:
    print(-1)
else:
    ans=0
    for i in range(len(s3)//2):
        if s3[i]!=s3[-i-1]:
            ans+=1
    print(ans)

Submission status: Runtime Error

Solution code:
def main():
    import sys

    def input(): return sys.stdin.readline().rstrip()

    s = input()
    n = len(s)
    cur_l = 0
    cur_r = n-1
    ans = 0
    cnt = 0
    while cur_l < cur_r:
        while s[cur_l] == 'x':
            cnt += 1
            cur_l += 1
        while s[cur_r] != s[cur_l]:
            if s[cur_r] != 'x':
                print(-1)
                return
            cur_r -= 1
            cnt -= 1
        ans += abs(cnt)
        cur_l += 1
        cur_r -= 1
        cnt = 0
        
    print(ans)   
    
        

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def xcounter(s,nx):
    l=len(s)
    cl=[0]*(nx)
    i=tc=0
    while tc<nx:
        if s[i]!='x':
            if i==l-1:cl[tc]=0
            else:
                i+=1
                c=0
                while i<l:
                    if s[i]=='x':
                        i+=1
                        c+=1
                    else:
                        cl[tc]=c
                        break
                else:cl[tc]=c
        tc+=1
    return cl

s=input()
rs=''
for c in s:
    if c!='x':rs=rs+c
lrs=len(rs)
if lrs==0:print(0)
else:
    er=False
    for c,rc in zip(rs,rs[::-1]):
        if c!=rc:
            er=True
            break
    if er:print(-1)
    else:
        newsl=newlr=''
        halflen=0
        if lrs%2==0:
            cr=lrs//2
            cl=cr-1
            tempid=0
            ild=idr=0
            for i,c in enumerate(s):
                if c!='x':tempid+=1
                if tempid==cl:
                    idl=i+1
                if tempid==cr:
                    idr=i+1
            newsl = s[:idl+1][::-1]
            newsr = s[idr:]
            halflen = lrs//2
        else:
            center = lrs//2
            tempid=0
            ocid=0
            for i,c in enumerate(s):
                if c!='x':tempid+=1
                if tempid==center:
                    ocid=i+1
                    break
            newsl = s[:ocid+1][::-1]
            newsr = s[ocid:]
            halflen = lrs//2 +1
        g=0
        for l,r in zip(xcounter(newsl,halflen),xcounter(newsr,halflen)):
            g += max(l,r)
        print(g)

Submission status: Runtime Error

Solution code:
def main():
    s = input()
    N = len(s)

    nox = []
    idxs = []
    ans = 0
    for i, c in enumerate(s):
        if c != "x":
            nox.append(c)
            idxs.append(i)
    
    if nox != nox[::-1]:
        print(-1)
        exit()
    

    if len(nox)%2 == 0:
        left = len(nox)//2 - 1
        right = len(nox)//2
        
        left_idx = idxs[left]
        right_idx = idxs[right]
        
    else:
        center = len(nox)//2
        left_idx = idxs[center]
        right_idx = idxs[center]

    old_left = -1
    old_right = -1
    while not (old_left == left_idx and old_right == right_idx):
        old_left = left_idx
        old_right = right_idx

        if s[left_idx] == s[right_idx]:
            if left_idx > 0:
                left_idx -= 1
            if right_idx < N-1:
                right_idx += 1
        elif s[left_idx] == "x":
            ans += 1
            if left_idx > 0:
                left_idx -= 1
        elif s[right_idx] == "x":
            ans += 1
            if right_idx < N-1:
                right_idx += 1

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys

s = sys.stdin.readline().strip()

ans = 0
l = 0
r = len(s) - 1

while l != r:
    print("left", l, "right", r)
    if s[l] == "x" and s[r] == "x":
        l += 1
        r -= 1
    # rにxを足したとみなし、lを進める
    elif s[l] == "x":
        l += 1
        ans += 1
    # lにxを足したとみなし、rを進める
    elif s[r] == "x":
        r -= 1
        ans += 1
    elif s[l] != s[r]:
        print(-1)
        sys.exit()
    else:
        l += 1
        r -= 1

print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i<j:
    while s[i]==s[j]=="x":
        i+=1
        j-=1
    if i>j:break    
    while s[i]=="x":
        i+=1
        ans+=1
    if i>j:break
    while s[j]=="x":
        j-=1
        ans+=1
    if i>j:break
    if s[i]!=s[j]:
        ans=-1
        break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s = input()

if s == s[::-1]:
    print(0)
    exit()

t = []

for i in range(len(s)):
    if s[i] != 'x':
        t.append(s[i])

if t != t[::-1]:
    print(-1)
    exit()

central_char = t[len(t)//2]

s = list(s)
s.insert(0, '*')
s.append('*')

central_position = 0

for i in range(len(s)):
    if s[i] == central_char:
        central_position = i

left = central_position - 1
right = central_position + 1
x_cnt = 0

while left > 0 or right < len(s)-1:
    if s[max(0, left)] == s[min(len(s), right)]:
        left -= 1
        right += 1
    else:
        x_cnt += 1
        if s[max(0, left)] == 'x':
            left -= 1
        else:
            right += 1

print(x_cnt)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i<j:
    while s[i]==s[j]=="x":
        i+=1
        j-=1
    if i>=len(s) or j<0:break    
    while s[i]=="x":
        i+=1
        ans+=1
        if i>=len(s):break
    if i>j:break
    while s[j]=="x":
        j-=1
        ans+=1
        if j<=-1:break
    if s[i]!=s[j]:
        ans=-1
        break
    if i>j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i<j:
    while s[i]==s[j]=="x":
        i+=1
        j-=1
    if i>j:break    
    while s[i]=="x":
        i+=1
        ans+=1
        if i>=len(s):break
    if i>j:break
    while s[j]=="x":
        j-=1
        ans+=1
        if j<=-1:break
    if s[i]!=s[j]:
        ans=-1
        break
    if i>j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i<j:
    while s[i]==s[j]=="x":
        i+=1
        j-=1
    while s[i]=="x":
        i+=1
        ans+=1
        if i==len(s):break
    if i>j:break
    while s[j]=="x":
        j-=1
        ans+=1
        if j==-1:break
    if s[i]!=s[j]:
        ans=-1
        break
    if i>j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i<j:
    while s[i]=="x":
        i+=1
        ans+=1
        if i>len(s):break
    if i==j:break
    while s[j]=="x":
        j-=1
        ans+=1
        if j<0:break
    if s[i]!=s[j]:
        ans=-1
        break
    if i==j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i!=j:
    while s[i]=="x":
        i+=1
        ans+=1
        if i>len(s):break
    if i==j:break
    while s[j]=="x":
        j-=1
        ans+=1
        if j<0:break
    if s[i]!=s[j]:
        ans=-1
        break
    if i==j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i!=j:
    while s[i]=="x":
        i+=1
        ans+=1
    if i==j:break
    while s[j]=="x":
        j-=1
        ans+=1
    if s[i]!=s[j]:
        ans=-1
        break
    if i==j:break
    i+=1
    j-=1
    if i>j:break
print(ans)

Submission status: Runtime Error

Solution code:
s=input()
i=0
j=len(s)-1
ans=0
while i!=j:

    while s[i]=="x":
        i+=1
        ans+=1
    if i==j:
        break
    while s[j]=="x":
        j-=1
        ans+=1
    if s[i]!=s[j]:
        ans=-1
        break
    if i==j:
        break
    i+=1
    j-=1
print(ans)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

s = sys.stdin.readline().strip()

# (元の文字列のindex, 文字）の配列
no_x = []
for i in range(len(s)):
    if s[i] == "x":
        continue
    no_x.append((i, s[i]))

len_no_x = len(no_x)
half = len_no_x // 2
for i in range(half):
    # x以外の文字が回文になっていないので不可能
    if no_x[i][1] != no_x[len_no_x - 1 - i][1]:
        print(-1)
        sys.exit()

# initから0まで走査し、元の文字列に左右対象になっていないxがある場合はxの挿入が必要
init = no_x[half][0]
# print("init", init)

ans = 0
l = 0
r = 0
# 元の文字列が偶数の場合、比較位置がずれる
if len_no_x % 2 == 0:
    l += 1

while init - l >= 0 or init + r < len(s):
    # print("left", init - l, "right", init + r)
    if init - l >= 0 and init + r < len(s):
        if s[init-l] == "x" and s[init+r] != "x":
            l += 1
            ans += 1
        elif s[init-l] != "x" and s[init+r] == "x":
            r += 1
            ans += 1
    elif init - l >= 0 and s[init-l] == "x":
        ans += 1
    elif init + r < len(s) and s[init+r] == "x":
        ans += 1
    l += 1
    r += 1

print(ans)

Submission status: Runtime Error

Solution code:
s = input()

if s == s[::-1]:
    print(0)
    exit()

t = []

for i in range(len(s)):
    if s[i] != 'x':
        t.append(s[i])

if t != t[::-1]:
    print(-1)
    exit()

central_char = t[len(t)//2]

s = list(s)
s.insert(0, '*')
s.append('*')

central_position = 0

for i in range(len(s)):
    if s[i] == central_char:
        central_position = i

left = central_position - 1
right = central_position + 1
x_cnt = 0

while left != 0 or right != len(s)-1:
    if s[max(0, left)] == s[min(len(s), right)]:
        left -= 1
        right += 1
    else:
        x_cnt += 1
        if s[max(0, left)] == 'x':
            left -= 1
        else:
            right += 1

print(x_cnt)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    s = input()
    n = len(s)
    ss = "".join(s.replace("x", ""))
    if ss != ss[::-1]:
        print(-1)
        exit()

    res = 0
    left = 0
    right = n - 1
    while left != right:
        if s[left] == s[right]:
            left += 1
            right -= 1
        else:
            if s[left] == "x":
                left += 1
            else:
                right -= 1
            res += 1
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
s = list(input().strip())
N = len(s)
a = ""
for i in range(N):
    if s[i]!="x":
        a += s[i]
if a==a[::-1]:
    flag = 1
else:
    flag = 0
if flag==1:
    n = len(a)
    C = [0 for _ in range(2*n+1)]
    for i in range(1,2*n+1,2):
        C[i] = a[i//2]
    cur = 0
    ind = 0
    for i in range(N):
        if s[i]=="x":
            C[cur]="x"
            cur += 2
        else:
            if 2*ind+1>cur:
                cur += 2
            ind += 1
    cnt = 0
    for i in range(0,n,2):
        if C[i]!=C[2*n-i]:
            cnt += 1
if flag==0:
    print(-1)
else:
    print(cnt)

Submission status: Runtime Error

Solution code:
s = input()

core = []

for c in s:
    if c != 'x':
        core.append(c)
l = 0
r = -1 if core == [] else len(core) - 1
while l <= r:
    if core[l] != core[r]:
        print(-1)
        exit()
    l += 1
    r -= 1

ans = 0
l = 0
r = len(s) - 1
while l <= r:
    lx = 0
    rx = 0
    while s[l] == 'x':
        l += 1
        lx += 1
    while s[r] == 'x':
        r -= 1
        rx += 1
    ans += abs(lx - rx)
    l += 1
    r -= 1
print(ans)

Submission status: Runtime Error

Solution code:
s = input()

core = []

for c in s:
    if c != 'x':
        core.append(c)
l = 0
r = 0 if core == [] else len(core) - 1
while l <= r:
    if core[l] != core[r]:
        print(-1)
        exit()
    l += 1
    r -= 1

ans = 0
l = 0
r = len(s) - 1
while l <= r:
    lx = 0
    rx = 0
    while s[l] == 'x':
        l += 1
        lx += 1
    while s[r] == 'x':
        r -= 1
        rx += 1
    ans += abs(lx - rx)
    l += 1
    r -= 1
print(ans)

Submission status: Runtime Error

Solution code:
s = input()

core = []

for c in s:
    if c != 'x':
        core.append(c)
l = 0
r = len(core) - 1
while l <= r:
    if core[l] != core[r]:
        print(-1)
        exit()
    l += 1
    r -= 1

ans = 0
l = 0
r = len(s) - 1
while l <= r:
    lx = 0
    rx = 0
    while s[l] == 'x':
        l += 1
        lx += 1
    while s[r] == 'x':
        r -= 1
        rx += 1
    ans += abs(lx - rx)
    l += 1
    r -= 1
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
    
    def check_palindrome(s):
        n = len(s)
        for i in range(n//2):
            if s[i] != s[n-1-i]:
                return False
        return True
    
    def find_center(s, cnt):
        num = 0
        n = len(s)
        for i in range(n):
            if s[i] != 'x':
                num += 1
            if num == cnt:
                return i

    def find_center_even(s, cnt):
        num = 0
        n = len(s)
        left, right = -1, -1
        for i in range(n):
            if s[i] != 'x':
                num += 1     
            if num == cnt:
                if left == -1:
                    left = i
                    print(f"left {left}")
            if num == cnt + 1:
                right = i
                print(f"right {right}")
                return (left + right) / 2
    
    def not_x_split(s):
        buf = []
        s += 'E'
        n = len(s)
        x_cnt = 0
        for i in range(n):
            if s[i] != 'x':
                buf.append(x_cnt)
                x_cnt = 0
            else:
                x_cnt += 1
        return buf



    def solve(s, buf):
        bufsize = len(buf)
        if bufsize % 2 == 0:
            cnt = bufsize // 2
            ind = find_center_even(s, cnt)
        else:
            cnt = (bufsize + 1) // 2
            ind = find_center(s, cnt)
        
        if ind % 1 == 0:
            left_s = s[:ind][::-1]
            right_s = s[ind+1:]
        else:
            left_s = s[:int(ind)+1][::-1]
            right_s = s[int(ind)+1:]

        # print(f"ind {ind}")
        # print(left_s)
        # print(right_s)
        left = not_x_split(left_s)
        right = not_x_split(right_s)
        # print(left)
        # print(right)
        assert len(left) == len(right)
        ans = 0
        for i in range(len(left)):
            ans += max(left[i], right[i]) - min(left[i], right[i])
        return ans

    
    s = input()
    if check_palindrome(s):
        print(0)
    else:
        buf = [char for char in s if char != 'x']
        if not check_palindrome(buf):
            print(-1)
        else:
            # print('solve')
            print(solve(s, buf))



if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
    
    def check_palindrome(s):
        n = len(s)
        for i in range(n//2):
            if s[i] != s[n-1-i]:
                return False
        return True
    
    def find_center(s, cnt):
        num = 0
        n = len(s)
        for i in range(n):
            if s[i] != 'x':
                num += 1
            if num == cnt:
                return i

    def find_center_even(s, cnt):
        num = 0
        n = len(s)
        left, right = -1, -1
        for i in range(n):
            if s[i] != 'x':
                num += 1     
            if num == cnt:
                if left == -1:
                    left = i
                    print(f"left {left}")
            if num == cnt + 1:
                right = i
                print(f"right {right}")
                return (left + right) / 2
    
    def not_x_split(s):
        buf = []
        s += 'E'
        n = len(s)
        x_cnt = 0
        for i in range(n):
            if s[i] != 'x':
                buf.append(x_cnt)
                x_cnt = 0
            else:
                x_cnt += 1
        return buf



    def solve(s, buf):
        bufsize = len(buf)
        if bufsize % 2 == 0:
            cnt = bufsize // 2
            ind = find_center_even(s, cnt)
        else:
            cnt = (bufsize + 1) // 2
            ind = find_center(s, cnt)
        
        if ind % 1 == 0:
            left_s = s[0:ind][::-1]
            right_s = s[ind+1:]
        else:
            left_s = s[0:int(ind)+1][::-1]
            right_s = s[int(ind)+1:]

        # print(f"ind {ind}")
        # print(left_s)
        # print(right_s)
        left = not_x_split(left_s)
        right = not_x_split(right_s)
        # print(left)
        # print(right)
        assert len(left) == len(right)
        ans = 0
        for i in range(len(left)):
            ans += max(left[i], right[i]) - min(left[i], right[i])
        return ans

    
    s = input()
    if check_palindrome(s):
        print(0)
    else:
        buf = [char for char in s if char != 'x']
        if not check_palindrome(buf):
            print(-1)
        else:
            # print('solve')
            print(solve(s, buf))



if __name__ == "__main__":
    main()