The Wayback Machine - https://web.archive.org/web/20220309022613/https://www.geeksforgeeks.org/check-if-string-can-be-made-palindrome-by-replacing-characters-in-given-pairs/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check if String can be made Palindrome by replacing characters in given pairs

  • Last Updated : 09 Mar, 2022

Given a string str and K pair of characters, the task is to check if string str can be made Palindrome, by replacing one character of each pair with the other.

Examples:

Input: str = “geeks”, K = 2, pairs = [[“g”, “s”], [“k”, “e”]]
Output: True
Explanation: 
Swap ‘s’ of “geeks” with ‘g’ using pair [‘g’, ‘s’] = “geekg”
Swap ‘k’ of “geekg” with ‘e’ using pair [‘k’, ‘e’] = “geeeg”
Now the resultant string is a palindrome. Hence the output will be True.

Input: str = “geeks”, K = 1, pairs =  [[“g”, “s”]]
Output: False
Explanation: Here only the first character can be swapped (g, s)
Final string formed will be : geekg, which is not a palindrome.

 

Naive Approach: The given problem can be solved by creating an undirected graph where an edge connecting (x, y) represents a relation between characters x and y.

  • Check for the condition of palindrome by validating the first half characters with later half characters.
  • If not equal:
    • Run a dfs from the first character and check if the last character can be reached.
  • Then, check for the second character with the second last character and so on.

Time Complexity: O(N * M), where N is size of target string and M is size of pairs array
Auxiliary Space: O(1)

Efficient Approach: The problem can be solved efficiently with the help of following idea:

Use a disjoint set data structure where each pair [i][0] and pair [i][1] can be united under the same set and search operation can be done efficiently. 
Instead of searching for the characters each time, try to group all the characters which are connected directly or indirectly, in the same set.

Below is the implementation of the above approach:

Python3




# Python code for the above approach:
  
class disjoint_set():
    def __init__(self):
  
        # string consist of only smallcase letters
        self.parent = [i for i in range(26)]
        self.rank = [1 for i in range(26)]
  
    def find_parent(self, x):
        if (self.parent[x] == x):
            return x
  
        self.parent[x] = self.find_parent(self.parent[x])
        return (self.parent[x])
  
    def union(self, u, v):
  
        p1 = self.find_parent(u)
        p2 = self.find_parent(v)
  
        if (p1 != p2):
  
            # rank of p1 smaller than p2
            if(self.rank[p1] < self.rank[p2]):
                self.parent[p1] = p2
  
            elif(self.rank[p2] < self.rank[p1]):
                self.parent[p2] = p1
  
            # rank of p2 equal to p1
            else:
                self.parent[p2] = p1
                self.rank[p1] += 1
  
    def connected(self, w1, w2):
  
        p1 = self.find_parent(w1)
        p2 = self.find_parent(w2)
  
        if (p1 == p2):
            return True
  
        return False
  
  
class Solution:
    def solve(self, target, pairs):
  
        size = len(target)
  
        # Create a object of disjoint set
        dis_obj = disjoint_set()
  
        for (u, v) in pairs:
  
            ascii_1 = ord(u) - ord('a')
            ascii_2 = ord(v) - ord('a')
  
            # Take union of both the characters
            dis_obj.union(ascii_1, ascii_2)
  
        left = 0
        right = size-1
  
        # Check for palindorme condition
        # For every character
        while(left < right):
  
            s1 = target[left]
            s2 = target[right]
  
            # If characters not same
            if (s1 != s2):
  
                # Convert to ascii value between 0-25
                ascii_1 = ord(s1) - ord('a')
                ascii_2 = ord(s2) - ord('a')
  
                # Check if both the words
                # Belong to same set
                if (not dis_obj.connected(ascii_1, ascii_2)):
                    return False
  
            left += 1
            right -= 1
  
        # Finally return True
        return (True)
  
  
if __name__ == '__main__':
  
    target = "geeks"
    pairs = [["g", "s"], ["e", "k"]]
  
    obj = Solution()
  
    ans = obj.solve(target, pairs)
    if (ans):
        print('true')
  
    else:
        print('false')
Output
true

Time Complexity: O(N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!