753. Cracking the Safe
Asked at 1Google22
Problem
A safe's password is n digits, each from 0 to k − 1, and the safe opens as soon as the last n digits typed match it. Return any shortest string that is guaranteed to open the safe at some point, i.e. contains every possible password as a substring.
Example: n = 2, k = 2 → "01100" (or another string of length 5 containing 00, 01, 10, 11)
Constraints: kⁿ ≤ 4096.
The shortest string containing every length-n password is a De Bruijn sequence of length kⁿ + n − 1. Nodes = length-(n−1) strings, each appended digit = an edge; an Eulerian circuit uses every edge (password) once. Hierholzer's DFS: append the edge digit after exploring it.
Complexity: O(kⁿ).
class Solution:
def crackSafe(self, n: int, k: int) -> str:
seen, out = set(), []
def dfs(node):
for d in map(str, range(k)):
edge = node + d
if edge not in seen:
seen.add(edge)
dfs(edge[1:])
out.append(d)
start = "0" * (n - 1)
dfs(start)
return "".join(out) + start
def covers(s, n, k):
return len({s[i:i + n] for i in range(len(s) - n + 1)}) == k ** n and len(s) == k ** n + n - 1
assert covers(Solution().crackSafe(1, 2), 1, 2)
assert covers(Solution().crackSafe(2, 2), 2, 2)
assert covers(Solution().crackSafe(3, 3), 3, 3)
class Solution {
private final Set<String> seen = new HashSet<>();
private final StringBuilder out = new StringBuilder();
public String crackSafe(int n, int k) {
String start = "0".repeat(n - 1);
dfs(start, k);
return out.append(start).toString();
}
private void dfs(String node, int k) {
for (int d = 0; d < k; d++) {
String edge = node + d;
if (seen.add(edge)) {
dfs(edge.substring(1), k);
out.append(d);
}
}
}
}
func crackSafe(n int, k int) string {
seen := map[string]bool{} // edges (n-digit codes) already used
out := []byte{}
var dfs func(node string)
dfs = func(node string) { // Hierholzer on the de Bruijn graph of (n-1)-digit nodes
for d := 0; d < k; d++ {
edge := node + string(rune('0'+d))
if !seen[edge] {
seen[edge] = true
dfs(edge[1:])
out = append(out, byte('0'+d))
}
}
}
start := strings.Repeat("0", n-1)
dfs(start)
return string(out) + start
}