Sentence Similarity II Problem
Description
LeetCode Problem 737.
We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].
Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [x_i, y_i] indicates that the two words x_i and y_i are similar.
Return true if sentence1 and sentence2 are similar, or false if they are not similar.
Two sentences are similar if:
- They have the same length (i.e., the same number of words)
sentence1[i]andsentence2[i]are similar.
Notice that a word is always similar to itself, also notice that the similarity relation is transitive. For example, if the words a and b are similar, and the words b and c are similar, then a and c are similar.
Example 1:
Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","good"],["fine","good"],["drama","acting"],["skills","talent"]]
Output: true
Explanation: The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
Example 2:
Input: sentence1 = ["I","love","leetcode"], sentence2 = ["I","love","onepiece"], similarPairs = [["manga","onepiece"],["platform","anime"],["leetcode","platform"],["anime","manga"]]
Output: true
Explanation: "leetcode" --> "platform" --> "anime" --> "manga" --> "onepiece".
Since "leetcode is similar to "onepiece" and the first two words are the same, the two sentences are similar.
Example 3:
Input: sentence1 = ["I","love","leetcode"], sentence2 = ["I","love","onepiece"], similarPairs = [["manga","hunterXhunter"],["platform","anime"],["leetcode","platform"],["anime","manga"]]
Output: false
Explanation: "leetcode" is not similar to "onepiece".
Constraints:
1 <= sentence1.length, sentence2.length <= 10001 <= sentence1[i].length, sentence2[i].length <= 20sentence1[i]andsentence2[i]consist of lower-case and upper-case English letters.0 <= similarPairs.length <= 2000similarPairs[i].length == 21 <= x_i.length, y_i.length <= 20x_iandy_iconsist of English letters.
Solution
Approach: Union-Find
Because similarity is transitive, two words are similar exactly when they are connected through a chain of pairs. In other words, every pair is an edge between two words, and similar words are the ones in the same connected component of that graph. Union-find (a disjoint-set forest) answers "are these two words in the same component?" quickly.
First, sentences of different lengths are never similar, so return false right away. Then, for each pair [x, y], add both words to the forest (each starts as its own root) and union their roots. Finally, compare the sentences position by position:
- equal words are always fine, even if the word never appears in
similarPairs; - otherwise both words must be in the forest and
findmust give the same root for both.
The tricky case is the first point: a word that is not in any pair is still similar to itself, so check w1 == w2 before looking anything up (in example 2, "I" and "love" appear in no pair). Words are case-sensitive, so "Good" and "good" are different words.
find uses path halving (point a node to its grandparent while walking up), which keeps the trees flat and every operation close to constant time.
Complexity: About O((n + p) · L) time, where n is the sentence length, p the number of pairs and L the word length (hashing a word costs O(L), and each find is close to constant time on average). O(p · L) extra space for the forest.
class Solution:
def areSentencesSimilarTwo(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
if len(sentence1) != len(sentence2):
return False
parent = {} # word -> parent word in the union-find forest
def find(x: str) -> str:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
for a, b in similarPairs:
parent.setdefault(a, a)
parent.setdefault(b, b)
parent[find(a)] = find(b)
for w1, w2 in zip(sentence1, sentence2):
if w1 == w2:
continue
if w1 not in parent or w2 not in parent or find(w1) != find(w2):
return False
return True