603. Sentence Similarity

A sentence can be represented as an array of words. For example, the sentence "She loves coding daily" can be represented as arr = ["She", "loves", "coding", "daily"].

Given two sentences, sentence1 and sentence2, each represented as a string array, and given an array of word pairs similarPairs, where similarPairs[i] = [xi, yi] indicates that the words xi and yi are similar.

Return true if sentence1 and sentence2 are similar, or false otherwise.

Two sentences are similar if:

  • They have the same length (i.e., the same number of words).
  • Each word sentence1[i] is similar to the corresponding word sentence2[i].

A word is always similar to itself. The similarity relation is not transitive, meaning if (a, b) and (b, c) are similar pairs, it does not imply (a, c) is similar.

Example 1:

Input:

sentence1 = ["fast", "runner", "wins"]  

sentence2 = ["quick", "sprinter", "triumphs"]  

similarPairs = [["fast", "quick"], ["runner", "sprinter"], ["wins", "triumphs"]]

Output: True

Explanation: The sentences have the same length, and each corresponding word has a similarity mapping.

Example 2:

Input:

sentence1 = ["brilliant"]  

sentence2 = ["brilliant"]  

similarPairs = []

Output: True

Explanation: A word is always similar to itself.

Now Your Turn!

Pick the correct output for the given input

Input:

sentence1 = ["happy", "journey"]  

sentence2 = ["joyful", "trip"]  

similarPairs = [["happy", "joyful"]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= sentence1.length, sentence2.length <= 1000
  • 1 <= sentence1[i].length, sentence2[i].length <= 20
  • Each word in sentence1 and sentence2 consists of English letters.
  • 0 <= similarPairs.length <= 1000
  • similarPairs[i].length == 2
  • 1 <= xi.length, yi.length <= 20
  • xi and yi consist of lowercase and uppercase English letters.
  • All the pairs (xi, yi) are distinct.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
bool areSentencesSimilar(vector<string>& sentence1, vector<string>& sentence2, vector<vector<string>>& similarPairs) {
// Your code goes here
}
};
Test Case

Input:

Sentence1
Sentence2
Similar Pairs