VOOZH about

URL: https://www.geeksforgeeks.org/dsa/equivalent-sentences/

⇱ Determining Word Equivalence between Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Determining Word Equivalence between Arrays

Last Updated : 23 Jul, 2025

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 = B

Input: 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:

  • We are using an unordered_map parent to represent relationships between words in the pairs.
  • The find function is a recursive function that finds the root of a word. If a word is not found in the parent map, it is considered its own root.
  • The unionWords function unions two words into the same set by updating their parent pointers. If the root of x is different from the root of y, x becomes the parent of y, connecting them in the same set.
  • In the areEquivalentWords function, it first checks if the sizes of arrays A[] and B[] are equal. If not, it returns "No" because arrays of different lengths cannot be equivalent.
  • It then iterates through the given pairs and uses unionWords to build equivalence sets.
  • Finally, it checks if the corresponding words in arrays A[] and B[] have the same root (representative). If they don't, it returns "No." Otherwise, it returns "Yes."

Below is the C++ implementation of the above approach:


Output
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)

Comment