Skip to content
Problem 753 · LeetCode 753(opens in a new tab)

Cracking the Safe

HardDepth-first search

A safe opens with a code of n digits, each digit from 0 to k − 1. You do not know the code. The safe watches what you type and, after every key press, compares the last n digits you have typed with the code. It opens as soon as they match.

Return a shortest string of digits that is sure to open the safe, whatever the code is. In other words, every possible code of length n must appear somewhere in it as n consecutive digits. Any shortest string is accepted.

Example 1

Input:  n = 2, k = 3
Output: "0221120100" (one valid answer)
Why:    all 9 codes 00..22 appear, in 9 + 1 = 10 digits
2 more examples and the constraints

Example 2

Input:  n = 1, k = 3
Output: "210" (one valid answer)
Why:    each one-digit code is typed once

Example 3

Input:  n = 3, k = 2
Output: "0011101000" (one valid answer)
Why:    the 8 codes 000..111 each appear once, in 8 + 2 = 10 digits

Constraints

  • 1 ≤ n ≤ 4
  • 1 ≤ k ≤ 10
  • kⁿ ≤ 4,096

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Backtrack over the next digitO(n·kⁿ) usually
  2. Euler circuit (Hierholzer)O(n·kⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for kⁿ = 4,096Verdict
Backtrack over the next digitO(n·kⁿ) usually
Passes; no guarantee
Euler circuit (Hierholzer)O(n·kⁿ)
Best; never undoes

n = code length, k = number of digit values.

Edge cases to test

  • n = 1. Every digit once: any order of 0..k − 1, length k.
  • k = 1. Only one code, n zeros: return "0" repeated n times.
  • Largest case. kⁿ = 4,096 codes: recursion goes 4,096 deep, so raise Python's limit.
  • Many answers. Any shortest string works; check coverage and length, not an exact string.

Common mistakes

  • Appending the digit before the recursive call, which can leave edges unused.
  • Forgetting to add the start node's n − 1 digits at the end.
  • Returning something longer than kⁿ + n − 1 digits by restarting the search.

How to talk through it

  1. 1Clarify. Is any shortest answer fine? What are the limits on n and k?
  2. 2Bound the length. kⁿ codes need at least kⁿ + n − 1 digits; each new digit must make a new window.
  3. 3Build the graph. Nodes are n − 1 digits, codes are edges; in-degree equals out-degree, so an Euler circuit exists.
  4. 4Run Hierholzer. DFS over unused edges, append digits in post-order, then add the start node.
  5. 5Test out loud. Run n = 1 and n = 2, k = 2 and check that every code appears once.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?