KatInterview

754. Cracking the Safe

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge is to find the shortest possible string that contains all k^n possible n-digit passwords (where digits are 0 to k-1) as substrings. This is a shortest common superstring problem for a specific set of strings. The key to making the superstring short is to maximize the overlap between consecutive passwords. An overlap of n-1 characters is the best we can do, which means each new password can be formed by appending just one new character to the previous n-1 digits.

Solution

Cracking the Safe in Python

class Solution:
    def crackSafe(self, n: int, k: int) -> str:
        # This problem can be modeled as finding an Eulerian path in a De Bruijn graph.
        # Nodes are sequences of n-1 digits.
        # Edges are sequences of n digits (the passwords).
        
        # A set to keep track of visited n-digit combinations (edges).
        visited = set()
        
        # 'ans' will store the sequence of appended digits in reverse order.
        ans = []

        # We use a post-order DFS (Hierholzer's algorithm) to find the Eulerian path.
        def dfs(node):
            # 'node' represents the current node in the De Bruijn graph (length n-1).
            for i in range(k):
                digit = str(i)
                edge = node + digit
                if edge not in visited:
                    visited.add(edge)
                    # The next node is the suffix of the current edge.
                    dfs(edge[1:])
                    # Post-order append: add the digit after exploring the path.
                    ans.append(digit)
        
        # The starting node has n-1 digits. For n=1, this is an empty string.
        start_node = "0" * (n - 1)
        dfs(start_node)
        
        # The final result is the starting prefix plus the reversed path of appended digits.
        # The number of appended digits will be k^n.
        return start_node + "".join(ans[::-1])

Cracking the Safe in Java

class Solution {
    private Set<String> visited;
    private StringBuilder ans;
    private int k;

    public String crackSafe(int n, int k) {
        // This problem can be modeled as finding an Eulerian path in a De Bruijn graph.
        // Nodes are sequences of n-1 digits.
        // Edges are sequences of n digits (the passwords).
        
        // Handle trivial case where only one combination is possible.
        if (k == 1) {
            return "0".repeat(n);
        }

        this.visited = new HashSet<>();
        this.ans = new StringBuilder();
        this.k = k;

        // The starting prefix has n-1 digits.
        // For n=1, this is an empty string.
        String startNode = "0".repeat(n - 1);
        
        // We start building the string with the initial prefix.
        ans.append(startNode);
        
        // We use a post-order DFS (Hierholzer's algorithm) to find the Eulerian path.
        dfs(startNode);
        
        return ans.toString();
    }

    private void dfs(String node) {
        for (int i = 0; i < k; ++i) {
            String edge = node + i;
            if (!visited.contains(edge)) {
                visited.add(edge);
                // The next node is the suffix of the current edge.
                String nextNode = edge.substring(1);
                dfs(nextNode);
                // Post-order append: add the digit that formed this edge.
                // This is slightly different from the C++/Python approach.
                // Here we build the string in forward order directly.
                ans.append(i);
            }
        }
    }
}

Cracking the Safe in C++

class Solution {
public:
    string crackSafe(int n, int k) {
        // This problem can be modeled as finding an Eulerian path in a De Bruijn graph.
        // Nodes are sequences of n-1 digits.
        // Edges are sequences of n digits (the passwords).
        
        // The total number of passwords (edges) is k^n.
        // The final string will have length k^n + n - 1.
        
        string startNode = string(n - 1, '0');
        unordered_set<string> visited;
        string path;

        // We use a post-order DFS (Hierholzer's algorithm) to find the Eulerian path.
        function<void(const string&)> dfs = 
            [&](const string& node) {
            for (int i = 0; i < k; ++i) {
                string edge = node + to_string(i);
                if (visited.find(edge) == visited.end()) {
                    visited.insert(edge);
                    // The next node is the suffix of the current edge.
                    // For n=1, node is empty, edge is one digit, substr(1) is empty.
                    string nextNode = edge.substr(1);
                    dfs(nextNode);
                    // Post-order append: add the digit after exploring the path.
                    path += to_string(i);
                }
            }
        };

        dfs(startNode);
        
        // The path is built in reverse, so we need to reverse it.
        reverse(path.begin(), path.end());
        
        // The final result is the starting prefix plus the path of appended digits.
        return startNode + path;
    }
};

Cracking the Safe in TypeScript

function crackSafe(n: number, k: number): string {
    // This problem can be modeled as finding an Eulerian path in a De Bruijn graph.
    // Nodes are sequences of n-1 digits.
    // Edges are sequences of n digits (the passwords).
    
    const visited = new Set<string>();
    const path: string[] = [];

    // We use a post-order DFS (Hierholzer's algorithm) to find the Eulerian path.
    const dfs = (node: string) => {
        for (let i = 0; i < k; i++) {
            const digit = String(i);
            const edge = node + digit;
            if (!visited.has(edge)) {
                visited.add(edge);
                // The next node is the suffix of the current edge.
                // For n=1, node is empty, edge is one digit, substr(1) is empty.
                const nextNode = edge.substring(1);
                dfs(nextNode);
                // Post-order append: add the digit after exploring the path.
                path.push(digit);
            }
        }
    };

    // The starting node has n-1 digits. For n=1, this is an empty string.
    const startNode = '0'.repeat(n - 1);
    dfs(startNode);

    // The path is built in reverse, so we need to reverse it.
    const pathSuffix = path.reverse().join('');

    // The final result is the starting prefix plus the path of appended digits.
    return startNode + pathSuffix;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.