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 recentndigits 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:
n = 1, k = 2
Output:
"10"
Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.
Example 2:
1
2
3
4
5
6
7
8
9
10
Input:
n = 2, k = 2
Output:
"01100"
Explanation: For each possible password:
- "00" is typed in starting from the 4th digit.
- "01" is typed in starting from the 1st digit.
- "10" is typed in starting from the 3rd digit.
- "11" is typed in starting from the 2nd digit.
Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.
The minimum string that unlocks the safe must contain every possible password of length n as a substring. This is equivalent to constructing a De Bruijn sequence of order n on k digits. We use DFS to build the sequence by visiting every possible combination exactly once.
classSolution {
public String crackSafe(int n, int k) {
StringBuilder ans =new StringBuilder();
Set<String> vis =new HashSet<>();
String start ="0".repeat(n - 1);
dfs(start, n, k, vis, ans);
ans.append(start);
return ans.toString();
}
voiddfs(String node, int n, int k, Set<String> vis, StringBuilder ans) {
for (int i = 0; i < k; i++) {
String next = node + i;
if (!vis.contains(next)) {
vis.add(next);
dfs(next.substring(1), n, k, vis, ans);
ans.append(i);
}
}
}
}
classSolution {
public: string crackSafe(int n, int k) {
string ans;
unordered_set<string> vis;
string start(n -1, '0');
dfs(start, n, k, vis, ans);
ans += start;
return ans;
}
voiddfs(string node, int n, int k, unordered_set<string>& vis, string& ans) {
for (int i =0; i < k; ++i) {
string next = node + to_string(i);
if (!vis.count(next)) {
vis.insert(next);
dfs(next.substr(1), n, k, vis, ans);
ans += to_string(i);
}
}
}
};