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 Optimized BFS with Early Pruning INPUT String s1 a b String s2 b a Positions differ! Input Values: s1 = "ab" s2 = "ba" Goal: Transform s1 to s2 using minimum swaps ALGORITHM STEPS 1 Initialize BFS Queue: ["ab"], Visited: {"ab"} 2 Find Mismatch s1[0]='a' != s2[0]='b' 3 Try Swaps Swap pos 0 with pos 1 4 Check Result "ba" == s2? YES! BFS Tree "ab" k=0 "ba" k=1 MATCH! FINAL RESULT Transformation a b Before SWAP b a After Output: 1 Confirmation: 1 swap transforms "ab" to "ba" [OK] Key Insight: BFS guarantees finding minimum swaps. At each level, we try all valid swaps from the first mismatch position. Early pruning: Only swap with characters that match the target, skip visited states. This reduces the search space significantly. Time: O(n! / (n-k)!), Space: O(n! / (n-k)!) for visited states. TutorialsPoint - K-Similar Strings | Optimized BFS with Early Pruning
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