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

# Similar String Groups Python Solution

> Tested Python solution for LeetCode 839 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 839, [Hard](/catalog/hard). 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/similar-string-groups/description/).

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

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

## Problem

Two strings, `X` and `Y`, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string `X`.

For example, `"tars"` and `"rats"` are similar (swapping at positions `0` and `2`), and `"rats"` and `"arts"` are similar, but `"star"` is not similar to `"tars"`, `"rats"`, or `"arts"`.

Together, these form two connected groups by similarity: `{"tars", "rats", "arts"}` and `{"star"}`. Notice that `"tars"` and `"arts"` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?

### Examples

```
Input: strs = ["tars","rats","arts","star"]
Output: 2
```

```
Input: strs = ["omv","ovm"]
Output: 1
```

### Constraints

* 1 \<= strs.length \<= 300
* 1 \<= strs\[i].length \<= 300
* strs\[i] consists of lowercase letters only.
* All the words in strs have the same length and are anagrams of each other.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2 * L + n * alpha(n)) for n words of length L
    # Space: O(n)
    def num_similar_groups(self, strs: list[str]) -> int:
        parent = list(range(len(strs)))
        rank = [0] * len(strs)

        def find(i: int) -> int:
            while parent[i] != i:
                parent[i] = parent[parent[i]]
                i = parent[i]
            return i

        def union(i: int, j: int) -> bool:
            root_i, root_j = find(i), find(j)
            if root_i == root_j:
                return False
            if rank[root_i] < rank[root_j]:
                root_i, root_j = root_j, root_i
            parent[root_j] = root_i
            if rank[root_i] == rank[root_j]:
                rank[root_i] += 1
            return True

        def similar(a: str, b: str) -> bool:
            first = second = -1
            for i, (x, y) in enumerate(zip(a, b, strict=True)):
                if x != y:
                    if second >= 0:
                        return False
                    if first < 0:
                        first = i
                    else:
                        second = i
            return first < 0 or (second >= 0 and a[first] == b[second])

        groups = len(strs)
        for i in range(len(strs)):
            for j in range(i + 1, len(strs)):
                if similar(strs[i], strs[j]) and union(i, j):
                    groups -= 1
        return groups
```

## Complexity

| Time | Space |
| - | - |
| O(n^2 \* L + n \* alpha(n)) for n words of length L | O(n) |

## Tags


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