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.
Input: S1 = “rat”, S2 = “cbb”, Str = “trrb”
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”
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:
Time Complexity: O(N)
Auxiliary space: O(1)