Approach
Depth-first search
For Cracking the Safe, 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
- 32 lines of Java from the credited upstream file 753.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 String crackSafe(int n, int k) {3 final String allZeros = "0".repeat(n);4 StringBuilder sb = new StringBuilder(allZeros);5 dfs((int) Math.pow(k, n), n, k, new HashSet<>(Arrays.asList(allZeros)), sb);6 return sb.toString();7 }8 9 private boolean dfs(int passwordSize, int n, int k, Set<String> seen, StringBuilder path) {10 if (seen.size() == passwordSize)11 return true;12 13 StringBuilder prefix = new StringBuilder(path.substring(path.length() - n + 1));14 15 for (char c = '0'; c < '0' + k; ++c) {16 prefix.append(c);17 final String prefixStr = prefix.toString();18 if (!seen.contains(prefixStr)) {19 seen.add(prefixStr);20 path.append(c);21 if (dfs(passwordSize, n, k, seen, path))22 return true;23 path.deleteCharAt(path.length() - 1);24 seen.remove(prefixStr);25 }26 prefix.deleteCharAt(prefix.length() - 1);27 }28 29 return false;30 }31}32