Approach
Breadth-first search
For K-Similar Strings, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 45 lines of Java from the credited upstream file 854.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int kSimilarity(String s1, String s2) {3 Queue<String> q = new ArrayDeque<>(List.of(s1));4 Set<String> seen = new HashSet<>(Arrays.asList(s1));5 6 for (int step = 0; !q.isEmpty(); ++step)7 for (int sz = q.size(); sz > 0; --sz) {8 final String curr = q.poll();9 if (curr.equals(s2))10 return step;11 for (final String child : getChildren(curr, s2)) {12 if (seen.contains(child))13 continue;14 q.offer(child);15 seen.add(child);16 }17 }18 19 return -1;20 }21 22 private List<String> getChildren(final String curr, final String target) {23 List<String> children = new ArrayList<>();24 char[] charArray = curr.toCharArray();25 int i = 0; 26 while (curr.charAt(i) == target.charAt(i))27 ++i;28 29 for (int j = i + 1; j < charArray.length; ++j)30 if (curr.charAt(j) == target.charAt(i)) {31 swap(charArray, i, j);32 children.add(String.valueOf(charArray));33 swap(charArray, i, j);34 }35 36 return children;37 }38 39 private void swap(char[] charArray, int i, int j) {40 final char temp = charArray[i];41 charArray[i] = charArray[j];42 charArray[j] = temp;43 }44}45