LeetCode 854, Hard. Topics: Hash Table, String, Breadth-First Search. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
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.
Examples
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.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026