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: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    s = input()
    N = len(s)
    t = s.replace('x','')
    if t == '':
        print(0)
        exit()

    M = len(t)
    
    if t[:M//2] != t[(M+1)//2:][::-1]:
        print(-1)
        exit()
    
    count = []
    for i in range(N):
        if s[i] != 'x':
            count.append(i)
    if M % 2 == 0:
        c = count[(M-1)//2]+count[M//2]
        c //= 2
        L = s[:c+1][::-1]
        R = s[c+1:]
    else:
        c = count[M//2]
        L = s[:c][::-1]
        R = s[c+1:]
    # print(L,R)
    ans = 0
    l,r = 0,0
    while 1:
        if l >= len(L):
            if r >= len(R):
                break
            else:
                ans += 1
                L += 'x'
                # l += 1
        elif r >= len(R):
            ans += 1
            R += 'x'
            # r += 1
        
        if L[l] == R[r]:
            l += 1
            r += 1
        else:
            if L[l] == 'x':
                ans += 1
                l += 1
            else:
                ans += 1
                r += 1
        # print(l,r)
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
import heapq
import re
import copy
from heapq import heapify, heappop, heappush
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def warshall_floyd(a, n):
    #d[i][j]: iからjへの最短距離
    d = copy.deepcopy(a)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

# ここから書き始める
s = input()
s2 = s.replace("x", "")
if s2 == s2[::-1]:
    print(s.count("x"))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
s = input()

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

for i in range(len(s)//2+1):
    left = s[l]
    right = s[r]
    
    if left == right:
        l += 1
        r -= 1
    else:
        if left == 'x':
            l += 1
            ans += 1
        elif right == 'x':
            r -= 1
            ans += 1
        else:
            print(-1)
            exit()

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
S = deque(input())

ans = 0
while len(S):
    if S[0] == S[-1]:
        if len(S) > 1:
            S.popleft()
            S.pop()
        else:
            S.pop()
    else:
        if S[0] != "x" and S[1] != "x":
            print(-1)
            exit()
        elif S[0] != "x":
            S.pop()
            ans += 1
        elif S[1] != "x":
            S.popleft()
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
s=input()
d=dict()
for i in s:
    if i in d:
        d[i]+=1
    else:
        d[i]=1
d['x']=0
p=0
for i in d.values():
    p+=i%2
    if p==2:
        print(-1)
        break
else:
    print(s.count('x') if p else s.count('x')-1)

Submission status: Wrong Answer

Solution code:
s = input()
LS = len(s)
mid = -(-LS//2)
left = s[:mid]
right = s[::-1][:mid]
lc = []
rc = []
lx = 0
rx = 0
for i in range(mid):
    if left[i]!='x':
        lc.append(left[i])
    if right[i]!='x':
        rc.append(right[i])
cnt = 0
if lc==rc or len(lc)+len(rc)==1:
    i = 0
    j = LS-1
    while j>i:
        if s[i]!=s[j]:
            if s[i]=='x':
                cnt+=1
                i +=1
            elif s[j]=='x':
                cnt+=1
                j -=1
        else:
            i +=1
            j -=1
    print(cnt)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
s = input()
#xを抜いてそれが回文ならOK
s_ext = s.replace('x', '')

top = s_ext[:int(len(s_ext)/2)]#前半
btm = s_ext[int(len(s_ext)/2)+1:]#後半
if( top == btm[::-1]):
    print(s.count('x')*2)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
s=input()

cnt=0
while len(s)>1:
    if s[0]==s[-1]:
        s= s[1:-1]
    elif s[0]=="x" and s[-1]!="x":
        s = s[1:]
        cnt +=1
    elif s[-1]=="x" and s[0]!="x":
        s = s[:-1]
        cnt +=1
    else:
        cnt=0
        break
print(cnt)

Submission status: Wrong Answer

Solution code:
s = str(input())
ns = s.replace('x', '')
l = len(ns)
if l == 0:
    print(0)
elif l == 1:
    idx = s.find(ns)
    print(abs(idx - (len(s) - idx - 1)))
else:
    cnt = 0
    L = []
    for i in range(l // 2):
        if ns[i] != ns[-(i+1)]:
            print(-1)
            break
        else:
            L.append(ns[i])
    else:
        if l % 2:
            L.append(ns[i+1])
        left = 0
        right = 0
        for c in L:
            left = s[left:].find(c)
            if right == 0:
                right = len(s) - s.rfind(c) - 1
            else:
                right = len(s) - (s[:-right].rfind(c) + right + 1)
            cnt += abs(left - right)
        print(cnt)

Submission status: Wrong Answer

Solution code:
s = str(input())
ns = s.replace('x', '')
l = len(ns)
if l == 0:
    print(0)
elif l == 1:
    idx = s.find(ns)
    print(abs(idx - (len(s) - idx - 1)))
else:
    cnt = 0
    L = []
    for i in range(l // 2):
        if ns[i] != ns[-(i+1)]:
            print(-1)
            break
        else:
            L.append(ns[i])
    else:
        L.append(ns[i+1])
        left = 0
        right = 0
        for c in L:
            left = s[left:].find(c)
            if right == 0:
                right = len(s) - s.rfind(c) - 1
            else:
                right = s[:-right].rfind(c)
            cnt += abs(left - right)
        print(cnt)

Submission status: Wrong Answer

Solution code:
s = str(input())
ns = s.replace('x', '')
l = len(ns)
if l == 0:
    print(0)
elif l == 1:
    idx = s.find(ns)
    print(len(s) - idx - 1)
else:
    cnt = 0
    L = []
    for i in range(l // 2):
        if ns[i] != ns[-(i+1)]:
            print(-1)
            break
        else:
            L.append(ns[i])
    else:
        L.append(ns[i+1])
        left = 0
        right = 0
        for c in L:
            left = s[left:].find(c)
            if right == 0:
                right = len(s) - s.rfind(c) - 1
            else:
                right = s[:-right].rfind(c)
            cnt += abs(left - right)
        print(cnt)

Submission status: Wrong Answer

Solution code:
s=input()

def ispalindrome(str): 
  return True if str == str[::-1] else False

if ispalindrome(s):
  print(0)
  exit()

elif 'x' not in s:
  print(-1)
  exit()

elif ispalindrome(s.replace('x',"")):
  print(s.count('x'))
  exit()

else:
  print(-1)

Submission status: Wrong Answer

Solution code:
s = input()
n = len(s)

sr = s.replace("x", "")

if sr != "".join(reversed(sr)):
    print(-1)
else:
    ans = 0
    l = 0
    r = -1
    while l < n and -r <= n:
        if s[l] == s[r]:
            l += 1
            r -= 1
            continue
        elif s[l] == "x" and s[r] != "x":
            ans += 1
            l += 1
        elif s[l] != "x" and s[r] == "x":
            ans += 1
            r -= 1
    print(ans)

Submission status: Wrong Answer

Solution code:
s = input()

count = [[c, s.count(c)] for c in "abcdefghijklmnopqrstuvwyz"]

sum_of_1 = 0
sum = 0
for c, cnt in count:
    if cnt == 1:
        sum_of_1 += 1
        check_ch = c
    sum += cnt

s_x = s.replace("x", "")

if s_x == s_x[::-1]:
    print(len(s) - sum)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys

# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
import heapq
import decimal
# import statistics
import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    s = list(input())

    characters = []

    for si in s:
        if si != "x":
            characters.append(si)

    flg = True
    odd = len(characters) % 2
    for i in range(len(characters) // 2):
        if characters[i] != characters[-i - 1]:
            flg = False

    if not flg:
        print(-1)
        exit(0)

    if len(characters) < 2:
        print(0)
        exit(0)

    idx = -1
    cntlist = []
    for c in characters:
        cnt = 0
        for i in range(idx + 1, len(s)):
            if c == s[i]:
                cntlist.append(cnt)
                idx = i
                break
            else:
                cnt += 1
    cntlist.append(len(s) - (len(characters) + sum(cntlist)))

    ans = 0
    for i in range(len(cntlist) // 2):
        ans += abs(cntlist[i] - cntlist[-i - 1])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
import heapq
import decimal
# import statistics
import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    s = list(input())

    characters = []

    for si in s:
        if si != "x":
            characters.append(si)

    flg = True
    odd = len(characters) % 2
    for i in range(len(characters) // 2):
        if characters[i] != characters[-i - 1]:
            flg = False

    if not flg:
        print(-1)
        exit(0)

    if len(characters) < 2:
        print(0)

    idx = -1
    cntlist = []
    for c in characters:
        cnt = 0
        for i in range(idx + 1, len(s)):
            if c == s[i]:
                cntlist.append(cnt)
                idx = i
                break
            else:
                cnt += 1
    cntlist.append(len(s) - (len(characters) + sum(cntlist)))

    ans = 0
    for i in range(len(cntlist) // 2):
        ans += abs(cntlist[i] - cntlist[-i - 1])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
s = input()
s_ = s.replace('x', '')
if s_ != s_[::-1]:
    print(-1)
    exit()
else:
    cnt = 0
    num = 0
    for i, a in enumerate(s):
        if i + cnt >= len(s)-1:
            break
        if a == s[-1-cnt]:
            cnt += 1
            continue
        if a == 'x':
            num += 1
            continue
        else:
            while s[-1-cnt] == 'x':
                cnt += 1
                num += 1

    print(num)

Submission status: Wrong Answer

Solution code:
s = input()

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

Submission status: Wrong Answer

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
## libs ##
from itertools import accumulate as acc
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    s = IS()
    t = s.replace('x', '')
    if t == t[::-1]:
        print(len(s)-len(t))
    else:
        print(-1)
    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log,sin,cos
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

s=list(ss())

dic=Counter(s)

sumnum=sum(dic.values())
sumnum-=dic["x"]

if sumnum==0:
    print(0)
    exit()
    
#print(dic,sumnum)
chk=Counter(s)
cnt=0
cntx=0
tmp=True
anschk=False
if sumnum%2==1:
    for i,j in enumerate(s):
        #print(dic,chk)
        if j!="x" and cnt<sumnum//2 and tmp:
            cnt+=1
            chk[j]-=1
        elif j=="x" and tmp:
            cntx+=1
            chk[j]-=1
        
        elif j!="x" and cnt==sumnum//2 and tmp:
            diccnt=0

            for p in dic:
                if p!="x" and p!=j:
                    if dic[p]==2*chk[p]:
                        diccnt+=1
                
                elif p==j:
                    if dic[p]==2*(chk[p]-1) +1:
                        diccnt+=1
                
                elif p=="x":
                    diccnt+=1
            #print(diccnt)
            cnt+=1
            if diccnt==len(list(dic)):
                print(max(cntx,dic["x"]-cntx)-min(cntx,dic["x"]-cntx))
                
                exit()
            else:
                print(-1)
                exit()

else:
    for i,j in enumerate(s):
        #print(dic,chk)
        if j!="x" and cnt<sumnum//2 -1  and tmp:
            cnt+=1
            chk[j]-=1
        elif j=="x" and tmp:
            cntx+=1
            chk[j]-=1
        
        elif j!="x" and cnt==sumnum//2 -1 and tmp:
            chk[j]-=1
            diccnt=0
            for p in dic:
                if p!="x":
                    if dic[p]==2*chk[p]:
                        diccnt+=1
                
                elif p=="x":
                    diccnt+=1
            #print(diccnt)
            cnt+=1
            if diccnt==len(list(dic)):
                print(max(cntx,dic["x"]-cntx)-min(cntx,dic["x"]-cntx))
                
                exit()
            else:
                print(-1)
                exit()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log,sin,cos
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

s=list(ss())

dic=Counter(s)

sumnum=sum(dic.values())
sumnum-=dic["x"]

if sumnum==0:
    print(0)
    exit()
    
#print(dic,sumnum)
chk=Counter(s)
cnt=0
cntx=0
tmp=True
anschk=False
if sumnum%2==1:
    for i,j in enumerate(s):
        #print(dic,chk)
        if j!="x" and cnt<sumnum//2 and tmp:
            cnt+=1
            chk[j]-=1
        elif j=="x" and cnt<sumnum//2 and tmp:
            #cntx+=1
            chk[j]-=1
        
        elif j!="x" and cnt==sumnum//2 and tmp:
            diccnt=0
            for p in dic:
                if p!="x" and p!=j:
                    if dic[p]==2*chk[p]:
                        diccnt+=1
                
                elif p==j:
                    if dic[p]==2*(chk[p]-1) +1:
                        diccnt+=1
                
                elif p=="x":
                    diccnt+=1
            #print(diccnt)
            cnt+=1
            if diccnt==len(list(dic)):
                print(max(cntx,dic["x"]-cntx)-min(cntx,dic["x"]-cntx))
                exit()
            else:
                print(-1)
                exit()

else:
    for i,j in enumerate(s):
        #print(dic,chk)
        if j!="x" and cnt<sumnum//2 and tmp:
            cnt+=1
            chk[j]-=1
        elif j=="x" and cnt<sumnum//2 and tmp:
            #cntx+=1
            chk[j]-=1
        
        elif j!="x" and cnt==sumnum//2 and tmp:
            diccnt=0
            for p in dic:
                if p!="x":
                    if dic[p]==2*chk[p]:
                        diccnt+=1
                
                elif p=="x":
                    diccnt+=1
            #print(diccnt)
            cnt+=1
            if diccnt==len(list(dic)):
                print(max(cntx,dic["x"]-cntx)-min(cntx,dic["x"]-cntx))
                exit()
            else:
                print(-1)
                exit()

Submission status: Wrong Answer

Solution code:
S = input()
N = len(S)
ans = []
check = []
for i in range(N):
    if S[i] != 'x':
        ans.append(S[i])
        check.append(i)
if ans != ans[::-1] or len(ans) == 0:
    print(-1)
    exit()
if len(ans)%2:
    cl,cr = check[len(ans)//2],check[len(ans)//2]
else:
    cl,cr = check[len(ans)//2-1],check[len(ans)//2]
cnt = 0
while 0 <= cl and cr <= N-1:
    if S[cl] == S[cr]:
        cl -= 1
        cr += 1
    elif S[cl] == 'x':
        cnt += 1
        cl -= 1
    else:
        cnt += 1
        cr += 1
cnt += max(cl+1,N-cr)
print(cnt)

Submission status: Wrong Answer

Solution code:
s = input()
t = s.replace("x", "")

flag = 1
for i in range(len(t)):
    if t[i] != t[~i]:
        flag = 0

if flag == 0:
    print(-1)
else:
    ans = 0
    t = s[::-1]
    c = 0
    for i in range(len(s)):
        if c >= len(t):
            if s[i] == "x":
                ans += 1
            continue
        if t[c] == s[i]:
            c += 1
            continue
        else:
            if s[i] == "x":
                ans += 1
                continue
            else:
                while t[c] == "x":
                    ans += 1
                    c += 1
                else:
                    c += 1
    print(ans//2)

Submission status: Wrong Answer

Solution code:
s = input()
LenS = len(s)
s = s.replace('x','')
L1 = list(s)
L2 = list(s)
L2.reverse()

if L1!=L2:
    print(-1)
else:
    ans = LenS-len(L1)
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from collections import deque
s = list(input())
cnt = Counter(s)
cha = ""
num = 0
if s == s[::-1]:
  print(0)
  exit()

for k, v in cnt.items():
  if k != "x" and v % 2:
    if cha == "":
      cha = k
      num = v//2 + 1
    else:
      print(-1)
      exit()
if cha == "" and "x" in cnt.keys() and cnt["x"]%2:
  cha = "x"
  num = cnt["x"]//2 + 1
idx = 0
cnt = 1
for i in range(len(s)):
  if s[i] == cha and cnt == num:
    idx = i
    break
  elif s[i] == cha and cnt != num:
    cnt += 1

t = deque([s[idx]])
p, q = idx-1, idx+1
while True:
  if 0 <= p and q < len(s):
    if s[p] == "x" and s[q] != "x":
      t.append("x")
      t.appendleft("x")
      p -= 1
    elif s[p] != "x" and s[q] == "x":
      t.append("x")
      t.appendleft("x")
      q += 1
    elif s[p] == s[q]:
      t.append(s[q])
      t.appendleft(s[p])
      p -= 1
      q += 1
    elif s[p] != "x" and s[q] != "x" and s[p] != s[q]:
      print(-1)
      exit()
  elif q == len(s):
    for i in range(p, -1, -1):
      if s[i] != "x":
        print(-1)
        exit()
      else:
        t.append("x")
        t.appendleft(s[i])
    break
  elif p == -1:
    for i in range(q, len(s)):
      if s[i] != "x":
        print(-1)
        exit()
      else:
        t.append(s[i])
        t.appendleft("x")
    break
  
print(len(t)-len(s))

Submission status: Wrong Answer

Solution code:
S=input()
n=len(S)
l=0
r=n-1
ans=0
while l+1<=r:
    if S[l]=='x' and S[l]!=S[r]:
        ans+=1
        l+=1
    elif S[r]=='x' and S[l]!=S[r]:
        ans+=1
        r-=1
    elif S[l]==S[r]:
        r-=1
        l+=1
    else:
        ans-=1
        break
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter
S=input()
if S==S[::-1]:
    print(0)
else:
    X=Counter(S)
    if 'x' in X.keys() and len(X.keys())==2:
        cnt=0
        ans=0
        for s in S:
            if s!='x':
                cnt+=1
            else:
                ans+=1
            if cnt==-(-(len(S)-X['x'])//2):
                break
        print(max(ans,X['x']-ans)-min(ans,X['x']-ans))
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
s = input()

s_no_x = ""
for i in range(len(s)):
    if s[i] != "x":
        s_no_x += s[i]

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

if not s_no_x:
    print(0)
    exit()

if len(s_no_x) % 2 == 0:
    non_x_count = 0
    for i in range(len(s)):
        if s[i] != "x":
            non_x_count += 1
        if non_x_count == len(s_no_x)//2:
            s1 = s[:i]
        if non_x_count == len(s_no_x)//2 + 1:
            s2 = s[i+1:]
            break
else:
    non_x_count = 0
    for i in range(len(s)):
        if s[i] != "x":
            non_x_count += 1
        if non_x_count == len(s_no_x)//2 + 1:
            s1 = s[:i]
            s2 = s[i+1:]
            break

ans = abs(len(s1) - len(s2))
for i in range(min(len(s1), len(s2))):
    if s[i] != s[-i-1]:
        ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
s = input()
def calc(s):
  ans = 0
  l = 0
  r = len(s)-1
  for i in range(len(s)):
    if l == r:
      return ans
    if s[l] == s[r]:
      l += 1
      r -= 1
    elif s[l]=='x' and s[r]!='x':
      l += 1
      ans += 1
    elif s[l]!='x' and s[r]=='x':
      r -= 1
      ans += 1
    else:
      return -1
  return ans

a = calc(s)
print(a)

Submission status: Wrong Answer

Solution code:
#WA
s = list(input())
ns = ''
cnt = 0
for i in range(len(s)):
    if s[i] != 'x':
        ns += s[i]
    else:cnt += 1

#回文にできるかどうか判定
if ns != ns[::-1]:
    print(-1)
    exit()
#もとから回文かどうか判定
if not ns or s == s[::-1]:
    print(0)
    exit()

mid = len(ns) // 2
mid_str = ns[mid]
#mid_ind = s.index(mid_str)
#print(mid_ind)
if mid != 0 and mid % 2 == 0:
    s.pop(mid)

count = 0
for i in range(len(s)):
    if s[i] != 'x':continue
    temp_ind = 2 * mid - i
    if temp_ind >= len(s) or temp_ind < 0:continue
    if s[temp_ind] == 'x':
        count += 1

#print(cnt, count)
print(cnt - count * 2)

Submission status: Wrong Answer

Solution code:
#WA
s = input()
ns = ''
cnt = 0
cnt1 = 0
for i in range(len(s)):
    if s[i] != 'x':
        ns += s[i]
    else:cnt += 1

if ns != ns[::-1]:
    print(-1)
    exit()
if not ns or s == s[::-1]:
    print(0)
    exit()

mid = len(ns) // 2
mid_str = ns[mid]
mid_ind = s.index(mid_str)
#print(mid_ind)

count = 0
for i in range(len(s)):
    if s[i] != 'x':continue
    temp_ind = 2 * mid_ind - i
    if temp_ind >= len(s) or temp_ind < 0:continue
    if s[temp_ind] == 'x':
        count += 1

#print(cnt, count)
print(cnt - count * 2)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = read().rstrip().decode()
ss = s[::-1]
cnt_ss = 0
cnt_s = 0
ans = 0
size = len(s) // 2
m = len(s)
for i in range(m):
    if s[cnt_s] == ss[cnt_ss]:
        if cnt_s != size:
            cnt_s += 1
        if cnt_ss != size:
            cnt_ss += 1
    elif s[cnt_s] == 'x':
        cnt_s += 1
        ans += 1
        m += 1
    elif ss[cnt_ss] == 'x':
        cnt_ss += 1
        ans += 1
        m -= 1
    else:
        print(-1)
        exit()
    size = m // 2
    if cnt_ss == cnt_s == size:
        break
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = readline().rstrip().decode()
ss = s[::-1]
cnt_ss = 0
cnt_s = 0
ans = 0
size = len(s) // 2
for i in range(len(s)):
    if s[cnt_s] == ss[cnt_ss]:
        if cnt_s < size:
            cnt_s += 1
        if cnt_ss < size:
            cnt_ss += 1
    elif s[cnt_s] == 'x':
        cnt_s += 1
        ans += 1
    elif ss[cnt_ss] == 'x':
        cnt_ss += 1
        ans += 1
    else:
        print(-1)
        exit()
    if cnt_ss == cnt_s == size:
        break
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = readline().rstrip().decode()
ss = s[::-1]
cnt_ss = 0
cnt_s = 0
ans = 0
size = len(s) // 2
for i in range(len(s)):
    if s[cnt_s] == ss[cnt_ss]:
        if cnt_s <= size:
            cnt_s += 1
        if cnt_ss <= size:
            cnt_ss += 1
    elif s[cnt_s] == 'x':
        if cnt_s <= size:
            cnt_s += 1
            ans += 1
    elif ss[cnt_ss] == 'x':
        if cnt_ss <= size:
            cnt_ss += 1
            ans += 1
    else:
        print(-1)
        exit()
print(ans)