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;
struct disjoint_set {
vector< int > parent, rank;
disjoint_set()
{
parent.resize(26);
rank.resize(26);
for ( int i = 0 ; i < 26 ; i++) {
parent[i] = i;
rank[i] = 1;
}
}
int find_parent( int v)
{
if (v == parent[v])
return v;
return parent[v] = find_parent(parent[v]);
}
void Union( int p1, int p2)
{
p1 = find_parent(p1);
p2 = find_parent(p2);
if (p1 != p2){
if (rank[p1] < rank[p2]){
parent[p1] = p2;
} else if (rank[p2] < rank[p1]){
parent[p2] = p1;
} else {
parent[p2] = p1;
rank[p1] += 1;
}
}
}
bool connected( int p1, int p2)
{
p1 = find_parent(p1);
p2 = find_parent(p2);
if (p1 == p2) return true ;
return false ;
}
};
bool solve(string& target, vector<pair< char , char > >& pairs)
{
disjoint_set dsu;
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 ;
}
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;
}
|
Python3
class disjoint_set():
def __init__( self ):
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):
if ( self .rank[p1] < self .rank[p2]):
self .parent[p1] = p2
elif ( self .rank[p2] < self .rank[p1]):
self .parent[p2] = 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)
dis_obj = disjoint_set()
for (u, v) in pairs:
ascii_1 = ord (u) - ord ( 'a' )
ascii_2 = ord (v) - ord ( 'a' )
dis_obj.union(ascii_1, ascii_2)
left = 0
right = size - 1
while (left < right):
s1 = target[left]
s2 = target[right]
if (s1 ! = s2):
ascii_1 = ord (s1) - ord ( 'a' )
ascii_2 = ord (s2) - ord ( 'a' )
if ( not dis_obj.connected(ascii_1, ascii_2)):
return False
left + = 1
right - = 1
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
{
private class DisjointSet
{
private int [] parent, rank;
public DisjointSet()
{
parent = new int [26];
rank = new int [26];
for ( int i = 0; i < 26; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
public int FindParent( int v)
{
if (v == parent[v])
return v;
return parent[v] = FindParent(parent[v]);
}
public void Union( int p1, int p2)
{
p1 = FindParent(p1);
p2 = FindParent(p2);
if (p1 != p2)
{
if (rank[p1] < rank[p2])
{
parent[p1] = p2;
}
else if (rank[p2] < rank[p1])
{
parent[p2] = p1;
}
else
{
parent[p2] = p1;
rank[p1] += 1;
}
}
}
public bool Connected( int p1, int p2)
{
p1 = FindParent(p1);
p2 = FindParent(p2);
if (p1 == p2) return true ;
return false ;
}
}
private static bool Solve( string target, List<Tuple< char , char >> pairs)
{
DisjointSet dsu = new DisjointSet();
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 ;
}
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" );
}
}
}
|
Java
import java.util.*;
public class GFG {
public static class DisjointSet {
private int [] parent, rank;
public DisjointSet() {
parent = new int [ 26 ];
rank = new int [ 26 ];
for ( int i = 0 ; i < 26 ; i++) {
parent[i] = i;
rank[i] = 1 ;
}
}
public int findParent( int v) {
if (v == parent[v]) return v;
return parent[v] = findParent(parent[v]);
}
public void union( int p1, int p2) {
p1 = findParent(p1);
p2 = findParent(p2);
if (p1 != p2) {
if (rank[p1] < rank[p2]) {
parent[p1] = p2;
} else if (rank[p2] < rank[p1]) {
parent[p2] = p1;
}
else {
parent[p2] = p1;
rank[p1] += 1 ;
}
}
}
public boolean connected( int p1, int p2) {
p1 = findParent(p1);
p2 = findParent(p2);
if (p1 == p2) return true ;
return false ;
}
}
public static boolean solve(String target, List<Map.Entry<Character, Character>> pairs) {
DisjointSet dsu = new DisjointSet();
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 ;
}
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>
class disjoint_set{
constructor(){
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){
if ( this .rank[p1] < this .rank[p2])
this .parent[p1] = p2
else if ( this .rank[p2] < this .rank[p1])
this .parent[p2] = 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
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)
dis_obj.union(ascii_1, ascii_2)
}
let left = 0
let right = size-1
while (left < right){
let s1 = target[left]
let s2 = target[right]
if (s1 != s2){
let ascii_1 = s1.charCodeAt(0) - 'a' .charCodeAt(0)
let ascii_2 = s2.charCodeAt(0) - 'a' .charCodeAt(0)
if (!dis_obj.connected(ascii_1, ascii_2))
return false
}
left += 1
right -= 1
}
return true
}
}
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' )
</script>
|
Time Complexity: O(N) Auxiliary Space: O(1)
|