#854
Hard Algorithms K similar strings
Hash Table String Breadth-First Search
40.6% acceptance
Feb 22, 2026
1175
63
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.
Solution
Rust
Time O(n²)
Space O(n)
/*
* 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
* Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba".
* Example 2:
* Input: s1 = "abc", s2 = "bca"
* Output: 2
* Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".
* 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.
*/
use std::collections::{HashSet, VecDeque};
impl Solution {
pub fn k_similarity(s1: String, s2: String) -> i32 {
if s1 == s2 { return 0; }
let mut visited = HashSet::new();
let mut queue = VecDeque::new();
queue.push_back((s1.clone(), 0));
visited.insert(s1.clone());
while let Some((s, swaps)) = queue.pop_front() {
let bytes_s: Vec<u8> = s.bytes().collect();
let bytes_t: Vec<u8> = s2.bytes().collect();
// Find first mismatch
let i = bytes_s.iter().zip(bytes_t.iter()).position(|(a, b)| a != b).unwrap();
// Try swapping with positions that match s2[i]
for j in i+1..bytes_s.len() {
if bytes_s[j] == bytes_t[i] {
let mut next = bytes_s.clone();
next.swap(i, j);
let ns = String::from_utf8(next).unwrap();
if ns == s2 { return swaps + 1; }
if visited.insert(ns.clone()) {
queue.push_back((ns, swaps + 1));
}
}
}
}
0
}
}