K-Similar Strings Problem
Description
LeetCode Problem 854.
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 1:
Input: s1 = "ab", s2 = "ba"
Output: 1
Example 2:
Input: s1 = "abc", s2 = "bca"
Output: 2
Example 3:
Input: s1 = "abac", s2 = "baca"
Output: 2
Example 4:
Input: s1 = "aabc", s2 = "abca"
Output: 2
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
Approach: Breadth-First Search over Strings
Treat every string as a node, and every swap as an edge. The smallest number of swaps from s1 to s2 is the shortest path, which BFS finds level by level: level 0 is s1, level 1 is everything one swap away, and so on. The first level that contains s2 gives the answer.
Trying all pairs of positions at every step would make the search huge. Two rules cut it down without losing the optimum:
- Fix the first wrong position. Let
ibe the first index wherecurrent[i] != s2[i]. Every earlier position is already right, and positionimust be fixed at some point, so we may fix it now. Only swaps that put the letters2[i]at positioniare tried. - Only take that letter from a wrong position. Swap
iwith aj > iwherecurrent[j] == s2[i]andcurrent[j] != s2[j]. Taking the letter from a position that is already correct would break that position and cost an extra swap later.
A seen set makes sure each string is expanded only once.
For s1 = "abc", s2 = "bca": position 0 needs b, so swap it in to get "bac" (1 swap); position 1 now needs c, giving "bca" (2 swaps).
Complexity: the number of strings visited is exponential in the worst case, but the two rules keep it small for n <= 20 with six letters. Each string costs O(n2) to expand (up to n swaps, each building a string of length n), where n is the length of s1. Space is O(n) per stored string.
class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
n = len(s1)
level = [s1] # every string reachable with `swaps` swaps
seen = {s1}
swaps = 0
while level:
next_level = []
for current in level:
if current == s2:
return swaps
i = 0
while current[i] == s2[i]: # first position that is still wrong
i += 1
for j in range(i + 1, n):
# Bring in the letter position i needs, taken from a position that is still wrong.
if current[j] == s2[i] and current[j] != s2[j]:
letters = list(current)
letters[i], letters[j] = letters[j], letters[i]
neighbor = "".join(letters)
if neighbor not in seen:
seen.add(neighbor)
next_level.append(neighbor)
level = next_level
swaps += 1
return swaps
Now write it from memory
Close the write-up and solve it yourself against the tests.