# Program to find smallest value of K for K-Similar Strings in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have two strings s and t. These two strings are K-similar if we can swap the positions of two letters in s exactly K times so that the resulting string is t. So, we have two anagrams s and t, we have to find the smallest K for which s and t are K-similar.

So, if the input is like s = "abc" t = "bac", then the output will be 1.

To solve this, we will follow these steps −

• Define a function neighbors() . This will take new_data

• for each index i and value c in new_data, do

• if c is not same as t[i], then

• come out from loop

• for j in range i+1 to size of new_data - 1, do

• if u[j] is same as t[i], then

• exchange new_data[i] new_data[j]

• generate a string by joining all elements from new_data and return, from next call, start again from this area

• exchange new_data[i] new_data[j]

• From the main method, do the following:

• q := make one queue ans insert pair (s, 0)

• seen := a new set from s

• while q is not empty, do

• (u, swap_cnt) := first item of q and delete it from q

• if u is same as t, then

• return swap_cnt

• for each v in neighbors(u as list), do

• if v is not in seen, then

• mark v as seen

• insert (v, swap_cnt+1) at the end of q

• return 0

## Example

Let us see the following implementation to get better understanding

from collections import deque
def solve(s, t):
def swap(data, i, j):
data[i], data[j] = data[j], data[i]

def neighbors(new_data):
for i, c in enumerate(new_data):
if c != t[i]: break

for j in range(i+1, len(new_data)):
if u[j] == t[i]:
swap(new_data, i, j)
yield "".join(new_data)
swap(new_data, i, j)

q = deque([(s, 0)])
seen = set(s)
while q:
u, swap_cnt = q.popleft()
if u == t:
return swap_cnt
for v in neighbors(list(u)):
if v not in seen:
q.append((v, swap_cnt+1))
return 0

s = "abc"
t = "bac"
print(solve(s, t))

## Input

"abc, bac"

## Output

1
Updated on 08-Oct-2021 07:24:31