Lexicographically smallest and largest string possible via Transitive mapping
Given two strings str1 and str2 containing lowercase letters. The task is to convert the given string str3 into lexicographically smallest and largest string that can be formed under the following conditions:
- The alphabet at the same indices in strings str1 and str2 are equivalent to each other.
- Equivalence follows the transitivity rule. meaning if x is equivalent to y and y is equivalent to z then x is equivalent to z.
- Every character is equivalent to itself.
Input: str1 = “abc”, str2 = “xyz”, str3 = “yzp”
Output: bcp yzp
Explanation: a, b, and c are equivalent to x, y and z respectively and vice-versa.
So the smallest string can be possible after replacing y with b and z with c.
There is no mapping found for p hence it is unchanged.
Similarly, biggest string possible will be “yzp”.
Input: str1 = “geeksgeeks”, str2 = “dedication”, str3 = “truegeek”
Output: aruaaaaa truttttt
Explanation: Above deduction can be implemented to find “aruaaaaa”
and “truttttt” as the lexicographic smallest and biggest string.
Approach: To solve the problem follow the below observations:
- Since we know that the characters having direct or indirect connections with each other have to be in the group hence it can be solved using disjoint set data structures.
- After the set is formed, we just have to check whether a character in the input string and an arbitrary character from ‘a’ to ‘z’ (for lexicographic smallest) and ‘z’ to ‘a’ (for lexicographic biggest) matches with it or not.
Follow the given steps to solve the problem:
- Implement a disjoint set data structure of size 26 as obj.
- If the lengths of str1 and str2 are not equal print “All characters not mapped”.
- Traverse str1 & str2 and perform union on its characters with each other.
- Traverse str3:
- For each character find the lexicographically smallest character to which it is mapped and the largest character to which it is mapped.
- Concatenate those characters into their respective strings.
- Store the result in a pair and return it as the final answer.
Below is the implementation for the above approach:
Time Complexity: O(M + N*26), where M and N are lengths of string str1 and str3.
Auxiliary Space: O(26)
Please Login to comment...