SDE & MLE Prep

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