753. Cracking the Safe

There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1.

While entering a password, the last n digits 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:

  1. n will be in the range [1, 4].
  2. k will be in the range [1, 10].
  3. k^n will be at most 4096.

 

Rust Solution

struct Solution;

use std::collections::HashSet;

impl Solution {
    fn crack_safe(n: i32, k: i32) -> String {
        let n = n as usize;
        let k = k as usize;
        let mut seq = vec![0; n];
        let mut visited: HashSet<Vec<u8>> = HashSet::new();
        visited.insert(seq.clone());
        let size = k.pow(n as u32);
        Self::dfs(1, &mut visited, &mut seq, k, n, size);
        seq.into_iter().map(|b| (b'0' + b) as char).collect()
    }
    fn dfs(
        start: usize,
        visited: &mut HashSet<Vec<u8>>,
        seq: &mut Vec<u8>,
        k: usize,
        n: usize,
        size: usize,
    ) -> bool {
        if visited.len() == size {
            return true;
        }
        for i in 0..k {
            let mut suffix = seq[start..].to_vec();
            suffix.push(i as u8);
            if visited.insert(suffix.clone()) {
                seq.push(i as u8);
                if Self::dfs(start + 1, visited, seq, k, n, size) {
                    return true;
                };
                seq.pop();
                visited.remove(&suffix);
            }
        }
        false
    }
}

#[test]
fn test() {
    let n = 1;
    let k = 2;
    let res = "01".to_string();
    assert_eq!(Solution::crack_safe(n, k), res);
    let n = 2;
    let k = 2;
    let res = "00110".to_string();
    assert_eq!(Solution::crack_safe(n, k), res);
}

Having problems with this solution? Click here to submit an issue on github.