Given three strings, S1, S2, and S3. The characters on the identical index in S1 and S2 are thought-about equal and comply with the transitive property. For instance, if S1 = ‘abc’ and S2 = ‘xcd’, then characters {a, x} are equal, and characters {b, c, d} are equal, the duty is to seek out and print the lexicographically smallest string you can receive from S3 by altering its characters to another equal character obtained from S1 and S2. In different phrases, that you must change the characters in S3 with their equal characters from S1 and S2 whereas sustaining the lexicographic order.
Examples:
Enter: S1 = “abc” , S2 = “xyz” , S3 =” xazy”
Output: aacb
Rationalization: ‘x’ changed by ‘a’, ‘y’ is changed by ‘b’ and ‘z’ is changed by ‘c’Enter: S1 = “abc” , S2 = “xcd” , S3 =” xdc”
Output: abb
Rationalization: {a, x} are equal, and {b, c, d} are equal, so x is changed with a, d is changed with b, and c is changed with b.
Naïve method: We will resolve this downside utilizing the beneath concept:
- Create a graph the place s1[i] is linked with s2[i].
- then traverse string s3 from left to proper and do the next.
- Name DFS for the s3[i] node and calculate the minimal character we are able to attain from node s3[i].
- assign this minimal character to s3[i].
- return string s3.
Time Complexity: O(N2)
Auxiliary Area: O ( 1 )
Environment friendly Strategy: We will resolve this downside optimally utilizing the beneath concept:
Thought is to make use of the DSU {Disjoint Set Union}. We will join the 2 characters that are mapped with one another and on the finish we traverse the s3 string and assign each s3[i] to the dad or mum of s3[i].
Observe the steps to resolve the issue:
- Make a node for each character.
- Traverse within the string s1 and do Union of s1[i] with s2[i].
- When all Union operation is being executed.
- Traverse within the s3 string and for each character of s3[i], assign it to its dad or mum.
- Return the s3 string.
Under is the C++ implementation of the above concept :
C++
|
Time Complexity: O(N)
Auxiliary Area: O(1), because the variety of nodes can by no means exceed 26 (variety of alphabets).
Final Up to date :
25 Jul, 2023
Like Article
Save Article