My issue
how can we not get 2 and 3 as output even though strings like “abxyzy” need 2 substrings to be removed
My code
def find_substring(s):
n = len(s)
longest_substring = ""
for i in range(n):
for j in range(i + 1, n):
if s[i] == s[j]:
substring = s[i:j + 1]
if len(substring) > len(longest_substring):
longest_substring = substring
return longest_substring
t = int(input())
for _ in range(t):
x = int(input())
s = input()
if(s==s[::-1]):
print(0)
else:
if(len(set(s))==len(s)):
print(-1)
elif(s[0]==s[-1]):
print(1)
elif(s.count(s[0])>1 or s.count(s[-1])>1):
g = find_substring(s)
if(g==g[::-1]):
print(1)
else:
print(2)
else:
g = find_substring(s)
if(g==g[::-1]):
print(2)
else:
print(3)
Problem Link: Palindrome Love Practice Coding Problem