Lexicographically smallest string formed by replacing characters according to the given relation
Given a string Str of N characters and two strings S1 and S2 of equal length where S1[i] and S2[i] are related to each other, the task is to find the lexicographically smallest string that can be obtained by replacing characters in Str with their related character.
Examples:
Input: S1 = “rat”, S2 = “cbb”, Str = “trrb”
Output: acca
Explanation: For the given S1 and S2, the characters that are related to each other are (r, c), (a, b), and (t, b).
Hence, in the given string, r can be replaced by c;
b can be replaced by a, and t can be replaced by a.
Hence, Str = “bcca”. Here, b again can be replaced by a.
Therefore, the final value of Str = “acca”, which is the smallest possible.
Input: S1 = “abc”, S2 = “xyz”, Str = “pqr”
Output: pqr
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. Thereafter, for each character in the given string, traverse the graph using DFS and find the smallest character among the connected vertices of the current character and replace them.
Time Complexity: O(N * M), where M represents the size of S1 or S2.
Auxiliary space: O(M)
Efficient Approach: The above approach can be optimally solved using the Disjoint Set Data Structure. The idea is to group all the characters having a relation into a same group which can be efficiently done using DSU. Here, it can be noted that during the union operation in DSU, the parent of a node should be chosen as the smallest character in the group to achieve the smallest lexicographic order.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 26;
class DisjointSet {
public :
int size;
int parent[N];
char chars[N];
DisjointSet()
{
size = 26;
for ( int i = 0; i < size; i++) {
parent[i] = i;
}
for ( int i = 0; i < 26; i++) {
chars[i] = 'a' + i;
}
}
int find_parent( int x)
{
if (parent[x] == x) {
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
void union_fun( int u, int v)
{
int p1 = find_parent(u);
int p2 = find_parent(v);
if (p1 != p2) {
if (p2 < p1) {
parent[p1] = p2;
}
else {
parent[p2] = p1;
}
}
}
};
string smallestLexStr(string S1, string S2, string Str)
{
DisjointSet ds;
int M = S1.length();
for ( int i = 0; i < M; i++) {
int idx1 = S1[i] - 'a' ;
int idx2 = S2[i] - 'a' ;
ds.union_fun(idx1, idx2);
}
for ( int i = 0; i < Str.length(); i++) {
int idx = ds.find_parent(Str[i] - 'a' );
Str[i] = ds.chars[idx];
}
return Str;
}
int main()
{
string S1 = "rat" ;
string S2 = "cbb" ;
string Str = "trrb" ;
cout << smallestLexStr(S1, S2, Str) << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static String smallestLexStr(String S1, String S2,
String Str)
{
DisjointSet ds = new DisjointSet();
int M = S1.length();
for ( int i = 0 ; i < M; i++) {
int idx1 = ( int )(S1.charAt(i)) - ( int )( 'a' );
int idx2 = ( int )(S2.charAt(i)) - ( int )( 'a' );
ds.union(idx1, idx2);
}
char [] arr = Str.toCharArray();
for ( int i = 0 ; i < arr.length; i++) {
int idx = ds.find_parent(( int )(arr[i])
- ( int )( 'a' ));
arr[i] = ds.chars[idx];
}
Str = "" ;
for ( char x : arr) {
Str += x;
}
return Str;
}
public static void main(String[] args)
{
String S1 = "rat" ;
String S2 = "cbb" ;
String Str = "trrb" ;
System.out.println(smallestLexStr(S1, S2, Str));
}
}
class DisjointSet {
public int size;
public int [] parent;
public char [] chars;
public DisjointSet()
{
size = 26 ;
parent = new int [size];
for ( int i = 0 ; i < size; i++) {
parent[i] = i;
}
chars = new char [size];
for ( int i = 0 ; i < 26 ; i++) {
chars[i] = ( char )(i + 97 );
}
}
public int find_parent( int x)
{
if (parent[x] == x) {
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
public void union( int u, int v)
{
int p1 = find_parent(u);
int p2 = find_parent(v);
if (p1 != p2) {
if (p2 < p1) {
parent[p1] = p2;
}
else {
parent[p2] = p1;
}
}
}
}
|
Python3
class DisjointSet:
def __init__( self ):
self .size = 26
self .parent = [i for i in range ( self .size)]
self .chars = [ chr (i + 97 ) for i in range ( self .size)]
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 (p2 < p1):
self .parent[p1] = p2
else :
self .parent[p2] = p1
def smallestLexStr(S1, S2, Str ):
ds = DisjointSet()
M = len (S1)
for i in range (M):
idx1 = ord (S1[i]) - ord ( 'a' )
idx2 = ord (S2[i]) - ord ( 'a' )
ds.union(idx1, idx2)
Str = list ( Str )
for i in range ( len ( Str )):
idx = ds.find_parent( ord ( Str [i]) - ord ( 'a' ))
Str [i] = ds.chars[idx]
Str = "".join( Str )
return Str
if __name__ = = "__main__" :
S1 = "rat"
S2 = "cbb"
Str = "trrb"
print (smallestLexStr(S1, S2, Str ))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
static string smallestLexStr( string S1, string S2, string Str){
DisjointSet ds = new DisjointSet();
int M = S1.Length;
for ( int i = 0 ; i < M ; i++){
int idx1 = ( int )(S1[i]) - ( int )( 'a' );
int idx2 = ( int )(S2[i]) - ( int )( 'a' );
ds.union(idx1, idx2);
}
List< char > arr = new List< char >(Str);
for ( int i = 0 ; i < arr.Count ; i++){
int idx = ds.find_parent(( int )(arr[i]) - ( int )( 'a' ));
arr[i] = ds.chars[idx];
}
Str = "" ;
foreach ( char x in arr){
Str += x;
}
return Str;
}
public static void Main( string [] args){
string S1 = "rat" ;
string S2 = "cbb" ;
string Str = "trrb" ;
Console.WriteLine(smallestLexStr(S1, S2, Str));
}
}
public class DisjointSet{
public int size;
public int [] parent;
public char [] chars;
public DisjointSet(){
size = 26;
parent = new int [size];
for ( int i = 0 ; i < size ; i++){
parent[i] = i;
}
chars = new char [size];
for ( int i = 0 ; i < 26 ; i++){
chars[i] = ( char )(i+97);
}
}
public int find_parent( int x){
if (parent[x] == x){
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
public void union( int u, int v){
int p1 = find_parent(u);
int p2 = find_parent(v);
if (p1 != p2){
if (p2 < p1){
parent[p1] = p2;
} else {
parent[p2] = p1;
}
}
}
}
|
Javascript
class DisjointSet {
constructor() {
this .size = 26;
this .parent = new Array( this .size);
for (let i = 0; i < this .size; i++) {
this .parent[i] = i;
}
this .chars = new Array( this .size);
for (let i = 0; i < 26; i++) {
this .chars[i] = String.fromCharCode(i + 97);
}
}
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 (p2 < p1) {
this .parent[p1] = p2;
}
else {
this .parent[p2] = p1;
}
}
}
}
function smallestLexStr(S1, S2, Str) {
let ds = new DisjointSet();
let M = S1.length;
for (let i = 0; i < M; i++) {
let idx1 = (S1.charAt(i)).charCodeAt(0) - 'a' .charCodeAt(0);
let idx2 = (S2.charAt(i)).charCodeAt(0) - 'a' .charCodeAt(0);
ds.union(idx1, idx2);
}
let arr = Str.split( "" );
for (let i = 0; i < arr.length; i++) {
let idx = ds.find_parent(arr[i].charCodeAt(0)
- 'a' .charCodeAt(0));
arr[i] = ds.chars[idx];
}
Str = "" ;
for (x of arr) {
Str += x;
}
return Str;
}
let S1 = "rat" ;
let S2 = "cbb" ;
let Str = "trrb" ;
console.log(smallestLexStr(S1, S2, Str));
|
Time Complexity: O(N)
Auxiliary space: O(1)
Last Updated :
07 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...