Suppose we have a lowercase alphabet string called s and also have a list of pairs called 'pairs'. Each element in pairs has two strings [a, b] where the character 'a' and 'b' are considered same. If there are two pairs like [a, b] and [b, c], then we can say a and b are equivalent also b and c are equivalent, so a and c are also equivalent. And any value a or b is equivalent to itself. We have to check whether s is a palindrome or not with the given equivalence relations.
So, if the input is like s = "raceckt" pairs = [["r", "t"], ["a", "k"], ["z", "x"]], then the output will be True, because "a" = "k", and "r" = "t" so the string can be "racecar" which is palindrome.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import defaultdict def solve(s, pairs): g = defaultdict(list) G = defaultdict(set) for x, y in pairs: g[x].append(x) g[y].append(y) g[x].append(y) g[y].append(x) def dfs(a, so_far): so_far.add(a) for elem in g[a]: if elem not in so_far: dfs(elem, so_far) for key in g: dfs(key, G[key]) for i in range(0, len(s) // 2): if s[i] == s[-1 - i] or (s[i] in G[s[-1 - i]] or s[-1 - i] in G[s[i]]): continue else: return False return True s = "raceckt" pairs = [["r", "t"], ["a", "k"], ["z", "x"]] print(solve(s, pairs))
"raceckt", [["r", "t"], ["a", "k"], ["z", "x"]]