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 to implements all functions // of the Disjoint Set Data Structure 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) { // find parent int p1 = find_parent(u); int p2 = find_parent(v); // if not same if (p1 != p2) { // if p2 smaller than p1 // then make parent p2 if (p2 < p1) { parent[p1] = p2; // make parent p1 } else { parent[p2] = p1; } } } }; // Function to find the lexicographically // smallest string formed by replacing // characters according to given relation string smallestLexStr(string S1, string S2, string Str) { // Create an object of DSU DisjointSet ds; int M = S1.length(); // Iterate through all given relations for ( int i = 0; i < M; i++) { // find ascii value of each character // and subtract from ascii value 'a' // so that index value is between 0-25 int idx1 = S1[i] - 'a' ; int idx2 = S2[i] - 'a' ; // take union of both indices ds.union_fun(idx1, idx2); } // Iterate through the string for ( int i = 0; i < Str.length(); i++) { // Find the smallest character // replacement among all relations int idx = ds.find_parent(Str[i] - 'a' ); Str[i] = ds.chars[idx]; } // Return the answer return Str; } // Driver code int main() { string S1 = "rat" ; string S2 = "cbb" ; string Str = "trrb" ; cout << smallestLexStr(S1, S2, Str) << endl; return 0; } // This code is contributed by lokeshpotta20. |
Java
// Java program to implement above approach import java.util.*; public class GFG { // Function to find the lexicographically // smallest string formed by replacing // characters according to given relation static String smallestLexStr(String S1, String S2, String Str) { // Create an object of DSU DisjointSet ds = new DisjointSet(); int M = S1.length(); // Iterate through all given relations for ( int i = 0 ; i < M; i++) { // find ascii value of each character // and subtract from ascii value a // so that index value between 0-25 int idx1 = ( int )(S1.charAt(i)) - ( int )( 'a' ); int idx2 = ( int )(S2.charAt(i)) - ( int )( 'a' ); // take union of both indices ds.union(idx1, idx2); } // Convert String into list of characters char [] arr = Str.toCharArray(); // Iterate through the list of characters for ( int i = 0 ; i < arr.length; i++) { // Find the smallest character // replacement among all relations int idx = ds.find_parent(( int )(arr[i]) - ( int )( 'a' )); arr[i] = ds.chars[idx]; } // Convert the list back to a string Str = "" ; for ( char x : arr) { Str += x; } // Return Answer return Str; } // Driver code public static void main(String[] args) { String S1 = "rat" ; String S2 = "cbb" ; String Str = "trrb" ; System.out.println(smallestLexStr(S1, S2, Str)); } } // Class to implements all functions // of the Disjoint Set Data Structure 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) { // find parent int p1 = find_parent(u); int p2 = find_parent(v); // if not same if (p1 != p2) { // if p2 smaller than p1 // then make parent p2 if (p2 < p1) { parent[p1] = p2; // make parent p1 } else { parent[p2] = p1; } } } } // This code is contributed by karandeep1234 |
Python3
# Python code to implement the above approach # Class to implements all functions # of the Disjoint Set Data Structure 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): # find parent p1 = self .find_parent(u) p2 = self .find_parent(v) # if not same if (p1 ! = p2): # if p2 smaller than p1 # then make parent p2 if (p2 < p1): self .parent[p1] = p2 # make parent p1 else : self .parent[p2] = p1 # Function to find the lexicographically # smallest string formed by replacing # characters according to given relation def smallestLexStr(S1, S2, Str ): # Create an object of DSU ds = DisjointSet() M = len (S1) # Iterate through all given relations for i in range (M): # find ascii value of each character # and subtract from ascii value a # so that index value between 0-25 idx1 = ord (S1[i]) - ord ( 'a' ) idx2 = ord (S2[i]) - ord ( 'a' ) # take union of both indices ds.union(idx1, idx2) # Convert String into list of characters Str = list ( Str ) # Iterate through the list of characters for i in range ( len ( Str )): # Find the smallest character # replacement among all relations idx = ds.find_parent( ord ( Str [i]) - ord ( 'a' )) Str [i] = ds.chars[idx] # Convert the list back to a string Str = "".join( Str ) # Return Answer return Str # Driver Code if __name__ = = "__main__" : S1 = "rat" S2 = "cbb" Str = "trrb" print (smallestLexStr(S1, S2, Str )) |
C#
// C# program to implement above approach using System; using System.Collections; using System.Collections.Generic; class GFG { // Function to find the lexicographically // smallest string formed by replacing // characters according to given relation static string smallestLexStr( string S1, string S2, string Str){ // Create an object of DSU DisjointSet ds = new DisjointSet(); int M = S1.Length; // Iterate through all given relations for ( int i = 0 ; i < M ; i++){ // find ascii value of each character // and subtract from ascii value a // so that index value between 0-25 int idx1 = ( int )(S1[i]) - ( int )( 'a' ); int idx2 = ( int )(S2[i]) - ( int )( 'a' ); // take union of both indices ds.union(idx1, idx2); } // Convert String into list of characters List< char > arr = new List< char >(Str); // Iterate through the list of characters for ( int i = 0 ; i < arr.Count ; i++){ // Find the smallest character // replacement among all relations int idx = ds.find_parent(( int )(arr[i]) - ( int )( 'a' )); arr[i] = ds.chars[idx]; } // Convert the list back to a string Str = "" ; foreach ( char x in arr){ Str += x; } // Return Answer return Str; } // Driver code public static void Main( string [] args){ string S1 = "rat" ; string S2 = "cbb" ; string Str = "trrb" ; Console.WriteLine(smallestLexStr(S1, S2, Str)); } } // Class to implements all functions // of the Disjoint Set Data Structure 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){ // find parent int p1 = find_parent(u); int p2 = find_parent(v); // if not same if (p1 != p2){ // if p2 smaller than p1 // then make parent p2 if (p2 < p1){ parent[p1] = p2; // make parent p1 } else { parent[p2] = p1; } } } } // This code is contributed by subhamgoyal2014. |
Javascript
// Javascript program to implement above approach // Class to implements all functions // of the Disjoint Set Data Structure 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) { // find parent let p1 = this .find_parent(u); let p2 = this .find_parent(v); // if not same if (p1 != p2) { // if p2 smaller than p1 // then make parent p2 if (p2 < p1) { this .parent[p1] = p2; // make parent p1 } else { this .parent[p2] = p1; } } } } // Function to find the lexicographically // smallest let formed by replacing // characters according to given relation function smallestLexStr(S1, S2, Str) { // Create an object of DSU let ds = new DisjointSet(); let M = S1.length; // Iterate through all given relations for (let i = 0; i < M; i++) { // find ascii value of each character // and subtract from ascii value a // so that index value between 0-25 let idx1 = (S1.charAt(i)).charCodeAt(0) - 'a' .charCodeAt(0); let idx2 = (S2.charAt(i)).charCodeAt(0) - 'a' .charCodeAt(0); // take union of both indices ds.union(idx1, idx2); } // Convert let into list of characters let arr = Str.split( "" ); // Iterate through the list of characters for (let i = 0; i < arr.length; i++) { // Find the smallest character // replacement among all relations let idx = ds.find_parent(arr[i].charCodeAt(0) - 'a' .charCodeAt(0)); arr[i] = ds.chars[idx]; } // Convert the list back to a string Str = "" ; for (x of arr) { Str += x; } // Return Answer return Str; } // Driver code let S1 = "rat" ; let S2 = "cbb" ; let Str = "trrb" ; console.log(smallestLexStr(S1, S2, Str)); // This code is contributed by Saurabh Jaiswal |
acca
Time Complexity: O(N)
Auxiliary space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!