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

# K-Similar Strings Python Solution with Tests

> Tested Python solution for LeetCode 854 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 854, [Hard](/catalog/hard). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Breadth-First Search](/catalog/topics/breadth-first-search). [View on LeetCode](https://leetcode.com/problems/k-similarity/description/).

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

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

## Problem

Strings `s1` and `s2` are `k`-**similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`.

Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`-**similar**.

### Examples

```
Input: s1 = "ab", s2 = "ba"
Output: 1
Explanation: The two strings are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba".
```

```
Input: s1 = "abc", s2 = "bca"
Output: 2
Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".
```

### Constraints

* 1 \<= s1.length \<= 20
* s2.length == s1.length
* s1 and s2 contain only lowercase letters from the set \{'a', 'b', 'c', 'd', 'e', 'f'}.
* s2 is an anagram of s1.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(n * n! * n) worst case, pruned heavily by only branching on the
    # first mismatched position and only swapping in a letter that belongs there
    # Space: O(n! * n) for the visited set of intermediate strings
    def k_similarity(self, s1: str, s2: str) -> int:
        queue: deque[str] = deque([s1])
        visited = {s1}
        steps = 0
        while queue:
            for _ in range(len(queue)):
                cur = queue.popleft()
                if cur == s2:
                    return steps
                i = 0
                while cur[i] == s2[i]:
                    i += 1
                chars = list(cur)
                for j in range(i + 1, len(chars)):
                    if chars[j] == s2[i] and chars[j] != s2[j]:
                        chars[i], chars[j] = chars[j], chars[i]
                        nxt = "".join(chars)
                        if nxt not in visited:
                            visited.add(nxt)
                            queue.append(nxt)
                        chars[i], chars[j] = chars[j], chars[i]
            steps += 1
        return steps
```

## Complexity

| Time | Space |
| - | - |
| O(n \* n! \* n) worst case, pruned heavily by only branching on the | O(n! \* n) for the visited set of intermediate strings |

## Tags


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