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
- 33 lines of Java from the credited upstream file 514.java.
- The implementation visibly relies on hash lookup, ordered 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 int findRotateSteps(String ring, String key) {3 Map<String, Integer> mem = new HashMap<>();4 return dfs(ring, key, 0, mem) + key.length();5 }6 7 8 private int dfs(final String ring, final String key, int index, Map<String, Integer> mem) {9 if (index == key.length())10 return 0;11 12 final String hashKey = ring + index;13 if (mem.containsKey(hashKey))14 return mem.get(hashKey);15 16 int ans = Integer.MAX_VALUE;17 18 19 20 21 for (int i = 0; i < ring.length(); ++i)22 if (ring.charAt(i) == key.charAt(index)) {23 final int minRotates = Math.min(i, ring.length() - i);24 final String newRing = ring.substring(i) + ring.substring(0, i);25 final int remainingRotates = dfs(newRing, key, index + 1, mem);26 ans = Math.min(ans, minRotates + remainingRotates);27 }28 29 mem.put(hashKey, ans);30 return ans;31 }32}33