![]() |
VOOZH | about |
Given two arrays A[] and B[] of strings and an array of pairs[] where each pair of words is equivalent and also follows transitive property (i.e. if x=y and y=z then x=z), determine whether each ith word of string A is equivalent to ith word of string B.
Examples:
Input: A = ["blue", "sky", "is"], B = ["pink", "sky", "of"], pairs = [["blue", "hi"],["pink", "hi"],["is", "of"]]
Output: Yes
Explanation: blue = "hi" and "pink" = "hi" so, "blue" = "pink" and "is" = "of" A = BInput: A = ["blue", "is"], B = ["pink", "sky"], pairs = [["pink", "blue"], ["is", "for"]]
Output: No
Explanation: pink= "blue" but "is" != "sky" so, A != B so, no
Approach: To solve the problem follow the below idea:
The approach to solve this problem is to use the concept of Disjoint Set Union (DSU), also known as Union-Find.
Below is the code explanation to solve the problem:
Below is the C++ implementation of the above approach:
yes
Time Complexity: O(N*M*log(N)), where N = length of vector A and M is the length of strings.
Auxiliary Space: O(N*M)