Grandma Capa Knits a Scarf (Codeforces 1582C)
Tags: Greedy, strings

Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.

Input: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines.The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string.The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.

Note: In the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome.

Sample Inputs:
5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky

Sample Outputs:
2
-1
0
3
2

Solution (Python):
def check(n, s, c):
    (l, r) = (0, n - 1)
    cnt = 0
    while l < r:
        if s[l] == s[r]:
            l += 1
            r -= 1
        elif s[l] == c:
            cnt += 1
            l += 1
        elif s[r] == c:
            cnt += 1
            r -= 1
        else:
            cnt = float('inf')
            break
    return cnt

def solve(n, s):
    (l, r) = (0, n - 1)
    (mindel, first, last) = (float('inf'), None, None)
    while l < r:
        if s[l] != s[r]:
            (first, last) = (s[l], s[r])
            break
        else:
            l += 1
            r -= 1
    if first and last:
        mindel = min(mindel, check(n, s, first))
        mindel = min(mindel, check(n, s, last))
        if mindel != float('inf'):
            print(mindel)
        else:
            print(-1)
    else:
        print(0)
for t in range(int(input())):
    n = int(input())
    s = input()
    solve(n, s)

Solution (Python):
for i in range(int(input())):
    n = int(input())
    s = input()
    index = -1
    (j1, j2) = (0, n - 1)
    index1 = -1
    index2 = -1
    while j1 < j2:
        if s[j1] != s[j2]:
            index1 = j1
            index2 = j2
            break
        j1 += 1
        j2 -= 1
    if index1 == -1 and index2 == -1:
        print(0)
    else:
        c1 = 0
        (pr_j1, pr_j2) = (j1, j2)
        lett1 = s[j1]
        lett2 = s[j2]
        flag1 = True
        while j1 < j2:
            if s[j1] != s[j2]:
                if s[j1] == lett1:
                    j1 += 1
                    c1 += 1
                elif s[j2] == lett1:
                    j2 -= 1
                    c1 += 1
                else:
                    flag1 = False
                    break
            else:
                j1 += 1
                j2 -= 1
        c2 = 0
        flag2 = True
        (j1, j2) = (pr_j1, pr_j2)
        while j1 < j2:
            if s[j1] != s[j2]:
                if s[j1] == lett2:
                    j1 += 1
                    c2 += 1
                elif s[j2] == lett2:
                    j2 -= 1
                    c2 += 1
                else:
                    flag2 = False
                    break
            else:
                j1 += 1
                j2 -= 1
        if flag1 == False and flag2 == False:
            print(-1)
        elif flag1 == True and flag2 == True:
            print(min(c1, c2))
        elif flag1 == False:
            print(c2)
        elif flag2 == False:
            print(c1)

Solution (Python):
from functools import *
from itertools import *
from collections import *
from math import *
from bisect import *

def factors(n):
    i = 1
    res = []
    while i <= sqrt(n):
        if n % i == 0:
            if n / i == i:
                res.append(i)
            else:
                res.append(i)
                res.append(n // i)
        i = i + 1
    return res

def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors

def largest_prime_factor(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n
for _ in range(int(input())):
    n = int(input())
    arr = list(input())

    def f(a):
        (i, j) = (0, n - 1)
        res = 0
        while i < j:
            if arr[i] == arr[j]:
                i += 1
                j -= 1
            elif arr[i] == a:
                i += 1
                res += 1
            elif arr[j] == a:
                j -= 1
                res += 1
            else:
                return -1
        return res
    (x, y) = (0, n - 1)
    while x < y and arr[x] == arr[y]:
        x += 1
        y -= 1
    (a1, a2) = (f(arr[x]), f(arr[y]))
    if a1 == -1 and a2 == -1:
        print(-1)
    elif a1 == -1:
        print(a2)
    elif a2 == -1:
        print(a1)
    else:
        print(min(a1, a2))