K-Similar Strings - Problem

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.

Input & Output

Example 1 — Basic Swap
$ Input: s1 = "ab", s2 = "ba"
Output: 1
💡 Note: Swap s1[0] and s1[1]: "ab" → "ba". One swap needed.
Example 2 — No Swaps Needed
$ Input: s1 = "abc", s2 = "abc"
Output: 0
💡 Note: Strings are already identical, no swaps needed.
Example 3 — Multiple Swaps
$ Input: s1 = "abcd", s2 = "cdab"
Output: 2
💡 Note: First swap(0,2): "abcd" → "cbad", then swap(1,3): "cbad" → "cdab".

Constraints

  • 1 ≤ s1.length ≤ 20
  • s2.length == s1.length
  • s1 and s2 contain only lowercase English letters
  • s1 and s2 are anagrams of each other

Visualization

Tap to expand
K-Similar Strings: Transform s1 into s2Input s1"ab"Target s2"ba"Swap positions0 and 1After 1 swap"ba"Answer: 1Find minimum number of swaps to make s1 equal s2
Understanding the Visualization
1
Input
Two anagram strings s1 and s2
2
Process
Find minimum character swaps needed
3
Output
Return smallest number k
Key Takeaway
🎯 Key Insight: Use BFS to explore string transformations level by level, ensuring minimum swaps are found first
Asked in
Google 45 Facebook 32 Amazon 28
23.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen