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: Find Master SequenceInput: n=2, k=2 (2-digit passwords using digits 0,1)00011011All possible 2-digit passwordsFind shortest sequenceMaster Sequence:0011000011110pos 0-1pos 1-2pos 2-3pos 3-4Sequence contains all passwords as substrings
Understanding the Visualization
1
Input
n=2, k=2 means 2-digit passwords using digits 0,1
2
Process
Find shortest sequence containing all passwords
3
Output
String that unlocks safe for any password
Key Takeaway
🎯 Key Insight: Transform into finding an Eulerian path in a de Bruijn graph where each password is an edge
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