# Lexicographically smallest string formed by replacing characters according to the given relation

• Last Updated : 28 Feb, 2022

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:

## 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``))`
Output
`acca`

Time Complexity: O(N)
Auxiliary space: O(1)

My Personal Notes arrow_drop_up