Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check string is palindrome or not with equivalent pairs in Python
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 equivalent. 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 through transitivity. Any character is equivalent to itself. We need 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 a palindrome.
Algorithm
To solve this problem, we will follow these steps ?
- Create a graph where equivalent characters are connected
- Use DFS to find all characters in each equivalence group
- For each pair of characters at mirror positions, check if they are equivalent
- Return True if all mirror pairs are equivalent, False otherwise
Implementation
from collections import defaultdict
def solve(s, pairs):
# Create adjacency list for the graph
g = defaultdict(list)
G = defaultdict(set)
# Build the graph with equivalent character pairs
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):
"""DFS to find all equivalent characters"""
so_far.add(a)
for elem in g[a]:
if elem not in so_far:
dfs(elem, so_far)
# Find all equivalence groups using DFS
for key in g:
dfs(key, G[key])
# Check palindrome with equivalent characters
for i in range(len(s) // 2):
left_char = s[i]
right_char = s[-1 - i]
# Check if characters are same or equivalent
if left_char == right_char or (left_char in G[right_char] or right_char in G[left_char]):
continue
else:
return False
return True
# Test the function
s = "raceckt"
pairs = [["r", "t"], ["a", "k"], ["z", "x"]]
print(solve(s, pairs))
True
How It Works
The algorithm works in three main phases ?
- Graph Construction: Build an undirected graph where each character points to all its equivalent characters
- Equivalence Groups: Use DFS to find connected components, creating groups of equivalent characters
- Palindrome Check: Compare characters at mirror positions and verify they belong to the same equivalence group
Example Walkthrough
For s = "raceckt" with pairs [["r", "t"], ["a", "k"], ["z", "x"]] ?
# Step-by-step example
s = "raceckt"
pairs = [["r", "t"], ["a", "k"], ["z", "x"]]
print("String:", s)
print("Pairs:", pairs)
print("Length:", len(s))
# Check each mirror pair
for i in range(len(s) // 2):
left = s[i]
right = s[-1-i]
print(f"Position {i}: '{left}' vs '{right}' at position {len(s)-1-i}")
print("\nResult:", solve(s, pairs))
String: raceckt Pairs: [['r', 't'], ['a', 'k'], ['z', 'x']] Length: 7 Position 0: 'r' vs 't' at position 6 Position 1: 'a' vs 'k' at position 5 Position 2: 'c' vs 'c' at position 4 Result: True
Conclusion
This solution uses graph theory to group equivalent characters and then checks palindrome conditions. The time complexity is O(V + E + n) where V is vertices, E is edges, and n is string length.
