884. K-Similar Strings
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the minimum number of swaps to transform string s1 into s2, where s1 and s2 are anagrams. This is a classic shortest path problem on a graph. The nodes of the graph are all possible strings that can be formed by permuting the characters of s1, and an edge exists between two strings if one can be transformed into the other by a single swap. Since each swap has a uniform cost of 1, Breadth-First Search (BFS) is the ideal algorithm to find the shortest path from s1 to s2.
Solution
K-Similar Strings in Python
import collections
class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
if s1 == s2:
return 0
# Step 1: Filter out matching characters to reduce problem size.
fs1_list = []
fs2_list = []
for i in range(len(s1)):
if s1[i] != s2[i]:
fs1_list.append(s1[i])
fs2_list.append(s2[i])
fs1 = "".join(fs1_list)
fs2 = "".join(fs2_list)
# Step 2: BFS to find the shortest path (minimum swaps).
queue = collections.deque([fs1])
visited = {fs1}
swaps = 0
while queue:
level_size = len(queue)
for _ in range(level_size):
curr = queue.popleft()
if curr == fs2:
return swaps
# Find the first position `i` where curr differs from fs2.
i = 0
while curr[i] == fs2[i]:
i += 1
# Find all possible swaps for curr[i] to make progress.
# We must place fs2[i] at position i.
for j in range(i + 1, len(curr)):
# Find a character that should be at position i.
if curr[j] == fs2[i]:
# Create the next state by swapping.
next_s_list = list(curr)
next_s_list[i], next_s_list[j] = next_s_list[j], next_s_list[i]
next_s = "".join(next_s_list)
if next_s not in visited:
visited.add(next_s)
queue.append(next_s)
swaps += 1
return -1 # Should not be reached
K-Similar Strings in Java
class Solution {
public int kSimilarity(String s1, String s2) {
if (s1.equals(s2)) {
return 0;
}
// Step 1: Filter out characters that are already in the correct position.
StringBuilder fs1_sb = new StringBuilder();
StringBuilder fs2_sb = new StringBuilder();
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
fs1_sb.append(s1.charAt(i));
fs2_sb.append(s2.charAt(i));
}
}
String fs1 = fs1_sb.toString();
String fs2 = fs2_sb.toString();
// Step 2: BFS to find the shortest path.
Queue<String> queue = new LinkedList<>();
queue.offer(fs1);
Set<String> visited = new HashSet<>();
visited.add(fs1);
int swaps = 0;
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
String curr = queue.poll();
if (curr.equals(fs2)) {
return swaps;
}
// Find the first character that is not in the correct position.
int j = 0;
while (j < curr.length() && curr.charAt(j) == fs2.charAt(j)) {
j++;
}
// Find a character to swap with curr.charAt(j).
// We need to place fs2.charAt(j) at this position.
for (int k = j + 1; k < curr.length(); k++) {
if (curr.charAt(k) == fs2.charAt(j)) {
char[] currChars = curr.toCharArray();
char temp = currChars[j];
currChars[j] = currChars[k];
currChars[k] = temp;
String next = new String(currChars);
if (!visited.contains(next)) {
visited.add(next);
queue.offer(next);
}
}
}
}
swaps++;
}
return -1; // Should not be reached
}
}
K-Similar Strings in C++
class Solution {
public:
int kSimilarity(string s1, string s2) {
if (s1 == s2) {
return 0;
}
// Step 1: Filter out characters that are already in the correct position.
string fs1 = "", fs2 = "";
for (int i = 0; i < s1.length(); ++i) {
if (s1[i] != s2[i]) {
fs1 += s1[i];
fs2 += s2[i];
}
}
// Step 2: BFS to find the shortest path.
queue<string> q;
q.push(fs1);
unordered_set<string> visited;
visited.insert(fs1);
int swaps = 0;
while (!q.empty()) {
int level_size = q.size();
for (int k = 0; k < level_size; ++k) {
string curr = q.front();
q.pop();
if (curr == fs2) {
return swaps;
}
// Find the first character that is not in the correct position.
int i = 0;
while (i < curr.length() && curr[i] == fs2[i]) {
i++;
}
// Find a character to swap with curr[i].
// We must swap curr[i] with a character that should be at position i (which is fs2[i]).
for (int j = i + 1; j < curr.length(); ++j) {
// If we find the character we need for position i, let's swap.
if (curr[j] == fs2[i]) {
string next = curr;
swap(next[i], next[j]);
if (visited.find(next) == visited.end()) {
visited.insert(next);
q.push(next);
}
}
}
}
swaps++;
}
return -1; // Should not be reached given the problem constraints
}
};
K-Similar Strings in TypeScript
function kSimilarity(s1: string, s2: string): number {
if (s1 === s2) {
return 0;
}
// Step 1: Filter out characters that are already in correct positions.
let fs1_arr: string[] = [];
let fs2_arr: string[] = [];
for (let i = 0; i < s1.length; i++) {
if (s1[i] !== s2[i]) {
fs1_arr.push(s1[i]);
fs2_arr.push(s2[i]);
}
}
const fs1 = fs1_arr.join('');
const fs2 = fs2_arr.join('');
// Step 2: BFS to find the shortest path.
let queue: string[] = [fs1];
const visited: Set<string> = new Set([fs1]);
let swaps = 0;
while (queue.length > 0) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const curr = queue.shift()!;
if (curr === fs2) {
return swaps;
}
// Find the first position `j` where curr differs from fs2.
let j = 0;
while (j < curr.length && curr[j] === fs2[j]) {
j++;
}
const currArr = curr.split('');
// Find all possible swaps for curr[j] to make progress.
// We need to place fs2[j] at this position.
for (let k = j + 1; k < currArr.length; k++) {
if (currArr[k] === fs2[j]) {
// Swap to create the next state.
[currArr[j], currArr[k]] = [currArr[k], currArr[j]];
const next = currArr.join('');
if (!visited.has(next)) {
visited.add(next);
queue.push(next);
}
// Backtrack the swap to explore other possibilities for `k`.
[currArr[j], currArr[k]] = [currArr[k], currArr[j]];
}
}
}
swaps++;
}
return -1; // Should not be reached
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.