Sentence Similarity II — LeetCode 737 Python Solution
- Problem
- #737
- Pattern
- Union-Find
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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] = [xi, yi] indicates that the two words xi and yi are similar.
Example
- 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.
Python solution
class Solution:
def areSentencesSimilarTwo(
self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]
) -> bool:
if len(sentence1) != len(sentence2):
return False
n = len(similarPairs)
p = list(range(n << 1))
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
words = {}
idx = 0
for a, b in similarPairs:
if a not in words:
words[a] = idx
idx += 1
if b not in words:
words[b] = idx
idx += 1
p[find(words[a])] = find(words[b])
for i in range(len(sentence1)):
if sentence1[i] == sentence2[i]:
continue
if (
sentence1[i] not in words
or sentence2[i] not in words
or find(words[sentence1[i]]) != find(words[sentence2[i]])
):
return False
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 737. Sentence Similarity II is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 737. Sentence Similarity II?
- LeetCode 737. Sentence Similarity II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 737. Sentence Similarity II?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 737. Sentence Similarity II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 737. Sentence Similarity II cover?
- LeetCode 737. Sentence Similarity II is tagged Depth-First Search, Breadth-First Search, Union Find, Array, Hash Table and String on LeetCode.
- Is LeetCode 737. Sentence Similarity II a premium problem?
- Yes. LeetCode 737. Sentence Similarity II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.