Problem 753

Abstract / Summary

A thief must open a safe by trying all possible codes following certain rules to minimize attempts.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0753.py

class Solution:
    def crackSafe(self, n: int, k: int) -> str:
        have = set()

        def deeper(code):
            result = ""
            for i in range(k):
                next = code[1:] + str(i)
                if next not in have:
                    have.add(next)
                    result += deeper(next)
                    result += str(i)
            return result

        initial = "0" * n
        return deeper(initial) + initial[1:]
16 lines | 472 bytes | submitted September 24, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (100k+ submissions).

Typical patterns to solve this problem:
  • Depth First Search
  • Eulerian Circuit
  • Graph Theory
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation generates a password that contains every possible combination of n digits in base k exactly once. It does this by constructing a De Bruijn sequence through a depth-first walk of an implicit graph where each node represents an (n-1)-length suffix and each edge corresponds to appending a digit. The final string returned is a cyclic sequence that can be opened at any point to reveal all kⁿ possible passwords.

Key Steps

Creation of the visited collection

have = set()

A hash-based set stores every (n-1)-length substring that has already been used as an edge label. This enables constant-time checks for whether a particular transition has been explored, preventing duplicate traversals.

Recursive depth-first exploration

def deeper(code):
    result = ""
    for i in range(k):
        next = code[1:] + str(i)
        if next not in have:
            have.add(next)
            result += deeper(next)
            result += str(i)
    return result

The function deeper receives the current node code, which is an (n-1)-character string. For each possible digit i from 0 to k-1, it forms the candidate edge next by dropping the first character of code and appending i. If this edge has not been visited, it is marked as visited, the recursion proceeds deeper from next, and the digit i is appended to the result after the recursive call. This post-order concatenation builds the sequence in reverse lexical order of the traversal.

Assembly of the final password string

initial = "0" * n
return deeper(initial) + initial[1:]

The algorithm starts from a node consisting of n zeroes, which guarantees that the generated sequence begins with the smallest possible prefix. After the recursive walk finishes, the function appends the tail of the initial node (all but its first character) to close the cycle, producing a linear representation of the De Bruijn sequence.

Edge Cases Handled

When n equals 1, the initial node becomes a single "0" and the recursion explores each digit exactly once, yielding a straightforward concatenation of all digits in order. The set have prevents revisiting the same single-character edge, ensuring the output contains each digit precisely once.

If k is 1, there is only one possible digit (0). The loop iterates once, the edge "0"* (n-1) + "0" is added to have, and the recursion terminates after a single call. The final string consists of n zeroes, which is the only valid sequence for this degenerate base.

The code also gracefully handles large values of n and k within recursion limits, because each recursive call consumes a new unique edge and the total number of calls equals the number of distinct edges (kⁿ). The visited set guarantees that the recursion never revisits an already processed edge, avoiding infinite loops.

Performance Optimizations

The use of a hash set for have provides constant-time membership tests, which is crucial when the algorithm must examine up to kⁿ edges. By marking an edge as visited before descending recursively, the implementation eliminates the need for backtracking checks after returning from deeper calls.

String construction occurs by concatenating the results of deeper calls with the current digit. Although Python strings are immutable, the recursion builds each segment only once, and the final concatenation happens in a linear pass as the call stack unwinds. This approach avoids repeated reallocation of large intermediate strings.

The algorithm leverages the implicit graph structure: it never materializes the full adjacency list of all possible nodes. Instead, each potential neighbor is generated on the fly from the current node, reducing memory overhead to the size of the visited set plus the recursion stack. This on-demand generation keeps the memory footprint proportional to the number of unique edges rather than the Cartesian product of all possible node combinations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a magical lock that needs a secret sequence of numbers to open. This computer code acts like a tiny detective trying to figure out all the possible combinations for that lock.

The code starts by keeping a list of every pattern it has already tried so it does not waste time repeating itself. It puts all the numbers in a row and starts testing out new numbers one by one. If it finds a pattern it has never seen before, it remembers that pattern and keeps moving forward. It works just like a path through a large maze, where the detective explores every single turn to make sure no corner is left unvisited. Once it has explored every single possibility, it glues all those tiny pieces together into one long string of numbers that acts like a master key. Everything stays very organized inside the computer until the detective has finished mapping the whole maze.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.11 | σ = 1.91

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
ruoru Rust
suxrobGM C#
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
ruoru Rust
suxrobGM C#
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
31 links | 18 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 solutions   September 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality