Cracking the Safe - Problem

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. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.

For example, the correct password is "345" and you enter in "012345":

  • After typing 0, the most recent 3 digits is "0", which is incorrect.
  • After typing 1, the most recent 3 digits is "01", which is incorrect.
  • After typing 2, the most recent 3 digits is "012", which is incorrect.
  • After typing 3, the most recent 3 digits is "123", which is incorrect.
  • After typing 4, the most recent 3 digits is "234", which is incorrect.
  • After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks.

Return any string of minimum length that will unlock the safe at some point of entering it.

Input & Output

Example 1 — Basic Case
$ Input: n = 1, k = 2
Output: 01
💡 Note: All passwords are single digits: 0, 1. String "01" contains both at positions 0 and 1.
Example 2 — Two Digits
$ Input: n = 2, k = 2
Output: 00110
💡 Note: All passwords: 00, 01, 10, 11. String "00110" contains: 00 at position 0-1, 01 at position 1-2, 11 at position 2-3, 10 at position 3-4.
Example 3 — Edge Case
$ Input: n = 1, k = 1
Output: 0
💡 Note: Only one possible password: 0. String "0" contains it at position 0.

Constraints

  • 1 ≤ n ≤ 4
  • 1 ≤ k ≤ 10
  • 1 ≤ kn ≤ 4096

Visualization

Tap to expand
Cracking the Safe - DFS Graph Approach INPUT _ _ De Bruijn Graph 0 1 0 1 1 0 n = 1 k = 2 Digits: [0, 1] ALGORITHM STEPS 1 Build Graph Each node = (n-1) digit seq 2 Start DFS Begin from node "0...0" 3 Euler Path Visit each edge exactly once 4 Build Result Append digits as visited DFS Traversal Start: node "" Visit edge 0 --> result="0" Visit edge 1 --> result="01" All edges visited [OK] Total: k^n = 2 passwords FINAL RESULT 01 UNLOCKED Output String "01" Passwords Covered: 0 1 Length = k^n + n - 1 = 2 + 1 - 1 = 2 Minimum length achieved! Key Insight: The problem is equivalent to finding an Eulerian path in a De Bruijn graph. Each n-digit password becomes an edge. DFS visits each edge exactly once, ensuring all k^n passwords are covered with the minimum possible string length. Time: O(k^n), Space: O(k^n). TutorialsPoint - Cracking the Safe | Optimized DFS with Graph Theory
Asked in
Google 15 Facebook 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen