Approach
Depth-first search
For Freedom Trail, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 35 lines of C++ from the credited upstream file 514.cpp.
- The implementation visibly relies on hash lookup.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 findRotateSteps(string ring, string key) {4 return dfs(ring, key, 0, {}) + key.length();5 }6 7 private:8 9 int dfs(const string& ring, const string& key, int index,10 unordered_map<string, int>&& mem) {11 if (index == key.length())12 return 0;13 14 const string hashKey = ring + to_string(index);15 if (const auto it = mem.find(hashKey); it != mem.cend())16 return it->second;17 18 int ans = INT_MAX;19 20 21 22 23 for (size_t i = 0; i < ring.length(); ++i)24 if (ring[i] == key[index]) {25 const int minRotates = min(i, ring.length() - i);26 const string& newRing = ring.substr(i) + ring.substr(0, i);27 const int remainingRotates =28 dfs(newRing, key, index + 1, std::move(mem));29 ans = min(ans, minRotates + remainingRotates);30 }31 32 return mem[hashKey] = ans;33 }34};35