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

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 solve(s, buf):
        n = len(s)
        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)

        left = set()
        right = set()        
        for i in range(n):
            if i < ind and s[i] == 'x':
                left.add(ind - i)
            if i > ind and s[i] == 'x':
                right.add(i - ind)

        ans = 0
        total = left | right
        # print(ind)
        # print(left, right, total)
        for elm in total:
            if elm not in left:
                ans += 1
        for elm in total:
            if elm not in right:
                ans += 1
        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: Wrong Answer

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 solve(s, buf):
        n = len(s)
        bufsize = len(buf)
        if bufsize % 2 == 0:
            cnt = bufsize // 2
            ind = find_center(s, cnt)
            ind += 0.5
        else:
            cnt = (bufsize + 1) // 2
            ind = find_center(s, cnt)

        left = set()
        right = set()        
        for i in range(n):
            if i < ind and s[i] == 'x':
                left.add(ind - i)
            if i > ind and s[i] == 'x':
                right.add(i - ind)

        ans = 0
        total = left | right
        # print(ind)
        # print(left, right, total)
        for elm in total:
            if elm not in left:
                ans += 1
        for elm in total:
            if elm not in right:
                ans += 1
        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: Wrong Answer

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

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

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 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 make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
s = input()
n = len(s)
if "x" not in s:
    if s == s[::-1]:
        print(0)
    else:
        print(-1)
else:
    ans = 0
    s2 = s
    i = 0
    while True:
        m = len(s2)
        if i >= m:
            break
        if s2[i] == "x" and s2[m - i - 1] != "x":
            s2 = s2[:i] + s2[i + 1:]
            ans += 1
        elif s2[i] != "x" and s2[m - i - 1] == "x":
            s2 = s2[:m - i - 1] + s2[m - i:]
            ans += 1
        else:
            i += 1
    print(ans)       

    # ans1 = 0
    # cnt1 = 0
    # for i in range(n):
    #     if s[i] == "x":
    #         if s[n - i - 1 + cnt1] != "x":
    #             ans1 += 1

    # ans2 = 0
    # for i in reversed(range(n)):
    #     print("n - i - 1 - ans2 =", n - i - 1 - ans2)
    #     if s[i] == "x":
    #         if s[n - i - 1 - ans2] != "x":
    #             ans2 += 1
    # print("ans1 =", ans1)
    # print("ans2 =", ans2)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline().rstrip
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np


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

	n=len(s)

	l=0
	r=n-1

	ans=0

	while l<r:

		if s[l]==s[r]:
			l+=1
			r-=1

		elif s[l]=="x":
			ans+=1
			l+=1

		elif s[r]=="x":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np


def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=0

	while l<r:

		if s[l]==s[r]:
			l+=1
			r-=1

		elif s[l]=="x":
			ans+=1
			l+=1

		elif s[r]=="x":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=0

	while l<r:

		if s[l]==s[r]:
			l+=1
			r-=1

		elif s[l]=="x":
			ans+=1
			l+=1

		elif s[r]=="x":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=0

	while s[l:r+1]:

		if s[l]==s[r]:
			l+=1
			r-=1

		elif s[l]=="x":
			ans+=1
			l+=1

		elif s[r]=="x":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=0

	while s[l:r+1]:

		if s[l]==s[r]:
			l+=1
			r-=1

		elif s[l]=="x":
			ans+=1
			l+=1

		elif s[r]=="x":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l/2 and tt<l/2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit()

	print(ans)

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l//2 and tt<l//2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit(0)

	print(str(ans))

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input().decode()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l//2 and tt<l//2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit(0)

	print(str(ans))

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input().decode()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l//2 and tt<l//2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit(0)

	print(ans)
	exit(0)

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	s=input().decode()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l//2 and tt<l//2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit(0)

	print(ans)

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

import numpy as np

def main():
	s=input().decode()
	t=s[::-1]
	#print(s,t)

	l=len(s)

	ss=0
	tt=0

	ans=0

	while ss<l//2 and tt<l//2:

		if s[ss]==t[tt]:
			ss+=1
			tt+=1

		elif s[ss]=="x":
			ans+=1
			l+=1
			ss+=1

		elif t[tt]=="x":
			ans+=1
			l+=1
			tt+=1

		else:
			print(-1)
			exit(0)

	print(ans)
























if __name__ == "__main__":
	main()

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
        cc = c+1
        L = s[:c+1][::-1]
        R = s[c+1:]
    else:
        c = count[M//2]
        L = s[:c][::-1]
        R = s[c+1:]
    ans, l, r = 0, 0, 0
    while 1:
        if l >= len(L):
            if r >= len(R):
                break
            else:
                ans += 1
                L += 'x'
        elif r >= len(R):
            ans += 1
            R += 'x'

        if L[l] == R[r]:
            l += 1
            r += 1
        else:
            if L[l] == 'x':
                ans += 1
                l += 1
            else:
                ans += 1
                r += 1
    if M % 2 == 1:
        print(ans)
    else:
        L = s[:cc+1][::-1]
        R = s[cc+1:]
        ans2, l, r = 0, 0, 0
        while 1:
            if l >= len(L):
                if r >= len(R):
                    break
                else:
                    ans2 += 1
                    L += 'x'
            elif r >= len(R):
                ans2 += 1
                R += 'x'

            if L[l] == R[r]:
                l += 1
                r += 1
            else:
                if L[l] == 'x':
                    ans2 += 1
                    l += 1
                else:
                    ans2 += 1
                    r += 1
        print(min(ans, ans2))


if __name__ == "__main__":
    main()

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
        cc = c+1
        L = s[:c+1][::-1]
        R = s[c+1:]
    else:
        c = count[M//2]
        L = s[:c][::-1]
        R = s[c+1:]
    ans, l, r = 0, 0, 0
    while 1:
        if l >= len(L):
            if r >= len(R):
                break
            else:
                ans += 1
                L += 'x'
        elif r >= len(R):
            ans += 1
            R += 'x'

        if L[l] == R[r]:
            l += 1
            r += 1
        else:
            if L[l] == 'x':
                ans += 1
                l += 1
            else:
                ans += 1
                r += 1
    if M % 2 == 1:
        print(ans)
    else:
        L = s[:cc][::-1]
        R = s[cc+1:]
        ans2, l, r = 0, 0, 0
        while 1:
            if l >= len(L):
                if r >= len(R):
                    break
                else:
                    ans2 += 1
                    L += 'x'
            elif r >= len(R):
                ans2 += 1
                R += 'x'

            if L[l] == R[r]:
                l += 1
                r += 1
            else:
                if L[l] == 'x':
                    ans2 += 1
                    l += 1
                else:
                    ans2 += 1
                    r += 1
        print(min(ans, ans2))


if __name__ == "__main__":
    main()