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
- 41 lines of C++ from the credited upstream file 854.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 int kSimilarity(string s1, string s2) {4 queue<string> q{{s1}};5 unordered_set<string> seen{{s1}};6 7 for (int step = 0; !q.empty(); ++step)8 for (int sz = q.size(); sz > 0; --sz) {9 string curr = q.front();10 q.pop();11 if (curr == s2)12 return step;13 for (const string& child : getChildren(curr, s2)) {14 if (seen.contains(child))15 continue;16 q.push(child);17 seen.insert(child);18 }19 }20 21 return -1;22 }23 24 private:25 vector<string> getChildren(string& curr, const string& target) {26 vector<string> children;27 int i = 0; 28 while (curr[i] == target[i])29 ++i;30 31 for (int j = i + 1; j < curr.length(); ++j)32 if (curr[j] == target[i]) {33 swap(curr[i], curr[j]);34 children.push_back(curr);35 swap(curr[i], curr[j]);36 }37 38 return children;39 }40};41