> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Sentence Similarity II Python Solution

> Tested Python solution for LeetCode 737 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 737, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Union Find](/catalog/topics/union-find). [View on LeetCode](https://leetcode.com/problems/sentence-similarity-ii/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 737   # by problem number
lcpy gen -s sentence_similarity_ii   # by problem name
```

## 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.

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]` and `sentence2[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.

### Examples

```
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.
```

```
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".
```

```
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 \<= 1000
* 1 \<= sentence1\[i].length, sentence2\[i].length \<= 20
* sentence1\[i] and sentence2\[i] consist of lower-case and upper-case English letters.
* 0 \<= similarPairs.length \<= 2000
* similarPairs\[i].length == 2
* 1 \<= xi.length, yi.length \<= 20
* xi and yi consist of English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sentence_similarity_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sentence_similarity_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O((n + m) * alpha(n)) for n pairs and m words
    # Space: O(n)
    def are_sentences_similar_two(
        self, sentence1: list[str], sentence2: list[str], similar_pairs: list[list[str]]
    ) -> bool:
        if len(sentence1) != len(sentence2):
            return False
        parent: dict[str, str] = {}

        def find(x: str) -> str:
            parent.setdefault(x, x)
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        for a, b in similar_pairs:
            parent.setdefault(a, a)
            parent.setdefault(b, b)
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[ra] = rb

        return all(x == y or find(x) == find(y) for x, y in zip(sentence1, sentence2, strict=True))
```

## Complexity

| Time | Space |
| - | - |
| O((n + m) \* alpha(n)) for n pairs and m words | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.