Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find smallest value of K for K-Similar Strings in Python
Given two anagram strings s and t, we need to find the minimum number of swaps required to transform s into t. Two strings are K-similar if we can swap exactly K pairs of characters in s to make it equal to t.
For example, if s = "abc" and t = "bac", we need only 1 swap to transform "abc" to "bac" by swapping characters at positions 1 and 2.
Algorithm
We use BFS (Breadth-First Search) to find the minimum number of swaps ?
neighbors() function: Generates all possible strings after one valid swap
Main BFS logic: Explores all possible transformations level by level
Early termination: Stops when we find the target string
Implementation
from collections import deque
def k_similar_strings(s, t):
def neighbors(string_data):
# Find first position where characters don't match
for i, char in enumerate(string_data):
if char != t[i]:
break
# Try swapping with all valid positions
for j in range(i + 1, len(string_data)):
if string_data[j] == t[i]:
# Perform swap
string_data[i], string_data[j] = string_data[j], string_data[i]
yield "".join(string_data)
# Undo swap for next iteration
string_data[i], string_data[j] = string_data[j], string_data[i]
# BFS to find minimum swaps
queue = deque([(s, 0)])
visited = {s}
while queue:
current_string, swap_count = queue.popleft()
# Check if we reached target
if current_string == t:
return swap_count
# Generate all possible next states
for neighbor in neighbors(list(current_string)):
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, swap_count + 1))
return 0
# Example usage
s = "abc"
t = "bac"
result = k_similar_strings(s, t)
print(f"Minimum swaps needed: {result}")
Minimum swaps needed: 1
How It Works
The algorithm works by exploring all possible single-character swaps in a breadth-first manner ?
Find mismatch: Locate the first position where
s[i] != t[i]Generate swaps: Try swapping
s[i]with all valid positions wheres[j] == t[i]BFS exploration: Use a queue to explore all possibilities level by level
Track visited: Avoid revisiting the same string configuration
Example with More Complex Input
# Test with a more complex example
s1 = "abcd"
t1 = "dcba"
result1 = k_similar_strings(s1, t1)
print(f"'{s1}' to '{t1}' requires: {result1} swaps")
s2 = "abcdef"
t2 = "fedcba"
result2 = k_similar_strings(s2, t2)
print(f"'{s2}' to '{t2}' requires: {result2} swaps")
'abcd' to 'dcba' requires: 2 swaps 'abcdef' to 'fedcba' requires: 3 swaps
Time and Space Complexity
Time Complexity: O(N! × N) in worst case, where N is string length
Space Complexity: O(N!) for storing visited states
Conclusion
This BFS approach guarantees finding the minimum number of swaps needed to transform one anagram into another. The algorithm efficiently explores all possible swap combinations while avoiding redundant computations through visited state tracking.
