Ninja has two strings ‘s’ and ‘t’ of same length, he knows that both strings are equivalent strings which means s[i], t[i] will follow all rules of any equivalence relation that are:
Ninja wants your help to find the lexicographically smallest equivalent string of a given string ‘str’.
Note:
1. String ‘s’, ‘t’ and ‘str’ consist of only lowercase English letters from ‘a’ – ‘z’.
2. String ‘s’ and ‘t’ are of same length.
For example:
Let s = “abc” , t = “xyz” and str = “xbc” then all strings that we can generate are “abc”, “abz”, “ayc”,”ayz”, “xbc”, “xbz”, “xyc”, “xyz” and smallest of all these is “abc”.
Input Format:
The first line of input contains an integer 'T' representing the number of test cases.
The first and the only line of each test case contains three space-separated strings ‘s’, ‘t’ and ‘str’.
Output Format :
For each test case, print a single line containing a single string denoting the smallest equivalent string of ‘str’.
The output for each test case is printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N, M <= 5000
Where ‘T’ is the number of test cases, ‘N’ is the length of string ‘s’ and ‘t’ and ‘M’ is the length of ‘str’.
Time limit: 1 second
2
coding ninjaa nijng
super aaaaa super
aiiaa
aaaaa
Test Case 1 : The smallest string that can be formed is:
‘n’ = ‘a’
‘i’ = ‘i’
‘j’ = ‘i’
‘g’ = ’a’
So, “aiiaa”
Test Case 2: The smallest string that can be formed is:
‘s’ = ‘u’ = ‘p’ = ‘e’ = ‘r’ = ‘a’
So “aaaaa” is shortest string
2
program awesome wqgmin
abcedf fdecba fanbfa
aqgain
aanbaa
Try to use union-find to merge the strings by prefix and get the lexicographically smallest equivalent string.
The idea here is to use disjoint set union or union-find data structure.
It provides the following capabilities. We are given several elements, each of which is a separate set. A DSU will have an operation to combine any two sets, and it will be able to tell in which set a specific element is.
Thus the basic interface of this data structure consists of only three operations:
We iterate both string ‘s’ and ‘t’ and union all characters placed at the same index i.e.
union(s[i],t[i]) where i goes from 0 -> s.length-1.
And to make the lexicographically smallest string we just return the find_set value of each character of ‘str’.
Algorithm:
Description of union_set(int a, int b)
Description of find_set(int v)
O(N + M), where ‘N’ is the length of string ’s’ and ‘t’ and ‘M’ is the length of string ‘str’.
We are iterating both strings, and storing in a DSU takes O(1) because total characters are 26 only.
O(1).
We are storing a single array parent of constant size 26.