Check if String can be made Palindrome by replacing characters in given pairs
Last Updated :
23 Jul, 2025
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:
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Structure for Disjoint set union
struct disjoint_set {
vector<int> parent, rank;
// Initialize DSU variables
disjoint_set()
{
parent.resize(26);
rank.resize(26);
for (int i = 0 ; i < 26 ; i++) {
parent[i] = i;
rank[i] = 1;
}
}
// Find parent of vertex 'v'
int find_parent(int v)
{
if (v == parent[v])
return v;
return parent[v] = find_parent(parent[v]);
}
// Union two sets containing vertices a and b
void Union(int p1, int p2)
{
p1 = find_parent(p1);
p2 = find_parent(p2);
if (p1 != p2){
// rank of p1 smaller than p2
if(rank[p1] < rank[p2]){
parent[p1] = p2;
}else if(rank[p2] < rank[p1]){
parent[p2] = p1;
// rank of p2 equal to p1
}else{
parent[p2] = p1;
rank[p1] += 1;
}
}
}
// Function for checking whether
// vertex a and b are in same set or not
bool connected(int p1, int p2)
{
p1 = find_parent(p1);
p2 = find_parent(p2);
if(p1 == p2) return true;
return false;
}
};
// Function solving the problem
bool solve(string& target, vector<pair<char, char> >& pairs)
{
// Initialize new instance of DSU
disjoint_set dsu; // Only lowercase letters
for (auto i : pairs) {
dsu.Union(i.first - 'a', i.second - 'a');
}
int lower = 0, upper = (int)target.length() - 1;
while (lower <= upper) {
if (!dsu.connected(target[lower] - 'a', target[upper] - 'a')) {
return false;
}
lower+=1;
upper-=1;
}
return true;
}
// Driver code
int main()
{
string target = "geeks";
vector<pair<char, char> > pairs
= { { 'g', 's' }, { 'e', 'k' } };
bool ans = solve(target, pairs);
if (ans) {
cout << "true\n";
}
else {
cout << "false\n";
}
return 0;
}
// This code is contributed by subhamgoyal2014.
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 palindrome 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')
C#
using System;
using System.Collections.Generic;
class Program
{
// Structure for Disjoint set union
private class DisjointSet
{
private int[] parent, rank;
// Initialize DSU variables
public DisjointSet()
{
parent = new int[26];
rank = new int[26];
for (int i = 0; i < 26; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
// Find parent of vertex 'v'
public int FindParent(int v)
{
if (v == parent[v])
return v;
return parent[v] = FindParent(parent[v]);
}
// Union two sets containing vertices a and b
public void Union(int p1, int p2)
{
p1 = FindParent(p1);
p2 = FindParent(p2);
if (p1 != p2)
{
// rank of p1 smaller than p2
if (rank[p1] < rank[p2])
{
parent[p1] = p2;
}
else if (rank[p2] < rank[p1])
{
parent[p2] = p1;
}
// rank of p2 equal to p1
else
{
parent[p2] = p1;
rank[p1] += 1;
}
}
}
// Function for checking whether
// vertex a and b are in same set or not
public bool Connected(int p1, int p2)
{
p1 = FindParent(p1);
p2 = FindParent(p2);
if (p1 == p2) return true;
return false;
}
}
// Function solving the problem
private static bool Solve(string target, List<Tuple<char, char>> pairs)
{
// Initialize new instance of DSU
DisjointSet dsu = new DisjointSet(); // Only lowercase letters
foreach (var i in pairs)
{
dsu.Union(i.Item1 - 'a', i.Item2 - 'a');
}
int lower = 0, upper = target.Length - 1;
while (lower <= upper)
{
if (!dsu.Connected(target[lower] - 'a', target[upper] - 'a'))
{
return false;
}
lower += 1;
upper -= 1;
}
return true;
}
// Driver code
static void Main(string[] args)
{
string target = "geeks";
List<Tuple<char, char>> pairs =
new List<Tuple<char, char>>()
{
new Tuple<char, char>('g', 's'),
new Tuple<char, char>('e', 'k')
};
bool ans = Solve(target, pairs);
if (ans)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
// This code is contributed by lokeshpotta20.
Java
import java.util.*;
public class GFG {
// Structure for Disjoint set union
public static class DisjointSet {
private int[] parent, rank;
// Initialize DSU variables
public DisjointSet() {
parent = new int[26];
rank = new int[26];
for (int i = 0; i < 26; i++) {
parent[i] = i;
rank[i] = 1;
}
}
// Find parent of vertex 'v'
public int findParent(int v) {
if (v == parent[v]) return v;
return parent[v] = findParent(parent[v]);
}
// Union two sets containing vertices a and b
public void union(int p1, int p2) {
p1 = findParent(p1);
p2 = findParent(p2);
if (p1 != p2) {
// rank of p1 smaller than p2
if (rank[p1] < rank[p2]) {
parent[p1] = p2;
} else if (rank[p2] < rank[p1]) {
parent[p2] = p1;
}
// rank of p2 equal to p1
else {
parent[p2] = p1;
rank[p1] += 1;
}
}
}
// Function for checking whether
// vertex a and b are in same set or not
public boolean connected(int p1, int p2) {
p1 = findParent(p1);
p2 = findParent(p2);
if (p1 == p2) return true;
return false;
}
}
// Function solving the problem
public static boolean solve(String target, List<Map.Entry<Character, Character>> pairs) {
// Initialize new instance of DSU
DisjointSet dsu = new DisjointSet(); // Only lowercase letters
for (Map.Entry<Character, Character> i : pairs) {
dsu.union(i.getKey() - 'a', i.getValue() - 'a');
}
int lower = 0, upper = target.length() - 1;
while (lower <= upper) {
if (!dsu.connected(target.charAt(lower) - 'a', target.charAt(upper) - 'a')) {
return false;
}
lower += 1;
upper -= 1;
}
return true;
}
// Driver code
public static void main(String[] args) {
String target = "geeks";
List<Map.Entry<Character, Character>> pairs = new ArrayList<>();
pairs.add(new AbstractMap.SimpleEntry<>('g', 's'));
pairs.add(new AbstractMap.SimpleEntry<>('e', 'k'));
boolean ans = solve(target, pairs);
if (ans) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
JavaScript
<script>
// JavaScript code for the above approach:
class disjoint_set{
constructor(){
// string consist of only smallcase letters
this.parent = new Array(26)
for(let i=0;i<26;i++){
this.parent[i] = i
}
this.rank = new Array(26).fill(1)
}
find_parent(x){
if (this.parent[x] == x)
return x
this.parent[x] = this.find_parent(this.parent[x])
return (this.parent[x])
}
union(u, v){
let p1 = this.find_parent(u)
let p2 = this.find_parent(v)
if (p1 != p2){
// rank of p1 smaller than p2
if(this.rank[p1] < this.rank[p2])
this.parent[p1] = p2
else if(this.rank[p2] < this.rank[p1])
this.parent[p2] = p1
// rank of p2 equal to p1
else{
this.parent[p2] = p1
this.rank[p1] += 1
}
}
}
connected(w1, w2){
let p1 = this.find_parent(w1)
let p2 = this.find_parent(w2)
if (p1 == p2)
return true
return false
}
}
class Solution{
solve(target, pairs){
let size = target.length
// Create a object of disjoint set
let dis_obj = new disjoint_set()
for (let [u, v] of pairs){
let ascii_1 = (u).charCodeAt(0) - ('a').charCodeAt(0)
let ascii_2 = (v).charCodeAt(0) - ('a').charCodeAt(0)
// Take union of both the characters
dis_obj.union(ascii_1, ascii_2)
}
let left = 0
let right = size-1
// Check for palindrome condition
// For every character
while(left < right){
let s1 = target[left]
let s2 = target[right]
// If characters not same
if (s1 != s2){
// Convert to ascii value between 0-25
let ascii_1 = s1.charCodeAt(0) - 'a'.charCodeAt(0)
let ascii_2 = s2.charCodeAt(0) - 'a'.charCodeAt(0)
// Check if both the words
// Belong to same set
if (!dis_obj.connected(ascii_1, ascii_2))
return false
}
left += 1
right -= 1
}
// Finally return true
return true
}
}
// driver code
let target = "geeks"
let pairs = [["g", "s"], ["e", "k"]]
let obj = new Solution()
let ans = obj.solve(target, pairs)
if (ans)
document.write('true')
else
document.write('false')
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem