HardNo. 0854

K-Similar Strings — LeetCode 854 Python Solution

Topics
Breadth-First Search, Hash Table, String
Reading time
5 min

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

Example

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

Python solution

PythonSolution
class Solution:
    def kSimilarity(self, s1: str, s2: str) -> int:
        def next(s):
            i = 0
            while s[i] == s2[i]:
                i += 1
            res = []
            for j in range(i + 1, n):
                if s[j] == s2[i] and s[j] != s2[j]:
                    res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :])
            return res

        q = deque([s1])
        vis = {s1}
        ans, n = 0, len(s1)
        while 1:
            for _ in range(len(q)):
                s = q.popleft()
                if s == s2:
                    return ans
                for nxt in next(s):
                    if nxt not in vis:
                        vis.add(nxt)
                        q.append(nxt)
            ans += 1

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 854. K-Similar Strings is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0126Word Ladder IIHard
0127Word LadderHard
0433Minimum Genetic MutationMedium
0721Accounts MergeMedium
0752Open the LockMedium
0839Similar String GroupsHard

Frequently asked questions

How hard is LeetCode 854. K-Similar Strings?

LeetCode 854. K-Similar Strings is rated Hard on LeetCode.

What is the time complexity of LeetCode 854. K-Similar Strings?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 854. K-Similar Strings?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 854. K-Similar Strings cover?

LeetCode 854. K-Similar Strings is tagged Breadth-First Search, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.