AlgoInsight

DSA problem

Cracking the Safe

HardEulerian CircuitPattern: Eulerian Circuittop300GoogleAmazonMicrosoftBloombergApple

There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password: it only checks the most recent n digits entered. For example, assuming the real password is "345", if you enter "012345", it would accept the password because the last n digits "345" match. Return any string of minimum length that will unlock the safe at some point of entering it.

The answer length is exactly k^n + (n - 1). Every length-n string over the alphabet must appear as a contiguous window somewhere in the output, so the output cannot be shorter than the number of distinct windows plus the overlap that the first window uses. Such a string is called a de Bruijn sequence B(k, n).

The classical construction reduces the problem to finding an Eulerian circuit on a carefully chosen directed graph. Build a graph whose vertices are the k^(n-1) strings of length n - 1 over the alphabet. From each vertex u add k outgoing edges, one per digit d in [0, k), going to the vertex obtained by dropping the first character of u and appending d. Each such edge corresponds to a unique length-n window — the concatenation of u and d — so traversing every edge exactly once covers every window exactly once.

The graph is Eulerian (every vertex has equal in- and out-degree k), so an Eulerian circuit exists. Run Hierholzer's algorithm starting from the all-zero vertex: DFS that consumes edges and pushes a digit to the result whenever an edge is fully exhausted. The output is the starting vertex's n - 1 digits followed by the reverse of the edge-emission sequence, giving the minimum-length de Bruijn-like password in O(k^n) time and space.

Examples

Example 1
Input: n = 1, k = 2
Output: "10"
Explanation: All single-digit passwords are 0 and 1; "10" contains both as windows of length 1.
Example 2
Input: n = 2, k = 2
Output: "01100"
Explanation: The four length-2 windows are "00", "01", "10", "11" — all four appear as consecutive substrings of "01100".
Example 3
Input: n = 2, k = 3
Output: "002210110"
Explanation: Nine windows ("00","01","02","10","11","12","20","21","22") must each appear; the answer has length 3^2 + 1 = 10, with the first window "00" using the implicit prefix.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

grapheulerian-circuitde-bruijnhierholzerdfs

Browse all DSA problems