753. Craking the Safe
There is a box protected by a password. The password is a sequence of ndigits where each digit can be one of the first kdigits 0, 1, ..., k-1.
While entering a password, the last ndigits entered will automatically be matched against the correct password.
For example, assuming the correct password is"345", if you type"012345", the box will open because the correct password matches the suffix of the entered password.
Return any password of minimum length that is guaranteed to open the box at some point of entering it.
Example 1:
Input:
n = 1, k = 2
Output: "01"
Note: "10" will be accepted too.Example 2:
Input: n = 2, k = 2
Output: "00110"
Note: "01100", "10011", "11001" will be accepted too.Note:
nwill be in the range[1, 4].kwill be in the range[1, 10].k^nwill be at most4096.
Thoughts:
DFS: A hashset and stringbuilder to edit the string. (Original Post)
start: n repeated "0".
transit: all the nodes that have not visited so far.
output: string in stringBuilder. (Guaranteed there is an answer after containing k^n visited distinct strings.
Greedy:
start: n repeated "0".
for loop through current digit j from k-1 to 0, append the last with the current digit, add the current substring and append current digit j to the answer if the current substring is not in visited (Original Post)
Code: DFS T: O(k^n);
Code: Greedy T:O(k^n * k)
Last updated
Was this helpful?