Cracking the Safe

hard backtracking graph euler circuit de bruijn

Problem

Given integers n and k, return a shortest string s of digits 0..k-1 such that every length-n combination appears at least once as a contiguous substring of s.

Inputn=2, k=2
Output"01100"
All four pairs 00, 01, 10, 11 appear as substrings.

def crackSafe(n, k):
    visited = set()
    res = []
    def dfs(node):
        for x in range(k):
            nxt = node + str(x)
            if nxt not in visited:
                visited.add(nxt)
                dfs(nxt[1:])
                res.append(str(x))
    start = '0' * (n - 1)
    dfs(start)
    return ''.join(res) + start
function crackSafe(n, k) {
  const visited = new Set();
  const res = [];
  function dfs(node) {
    for (let x = 0; x < k; x++) {
      const nxt = node + x;
      if (!visited.has(nxt)) {
        visited.add(nxt);
        dfs(nxt.slice(1));
        res.push(String(x));
      }
    }
  }
  const start = '0'.repeat(n - 1);
  dfs(start);
  return res.join('') + start;
}
class Solution {
  Set<String> visited = new HashSet<>(); StringBuilder res = new StringBuilder(); int K;
  public String crackSafe(int n, int k) {
    K = k;
    String start = "0".repeat(n - 1);
    dfs(start);
    return res.toString() + start;
  }
  void dfs(String node) {
    for (int x = 0; x < K; x++) {
      String nxt = node + x;
      if (!visited.contains(nxt)) {
        visited.add(nxt);
        dfs(nxt.substring(1));
        res.append(x);
      }
    }
  }
}
class Solution {
  unordered_set<string> visited; string res; int K;
public:
  string crackSafe(int n, int k) {
    K = k;
    string start(n - 1, '0');
    dfs(start);
    return res + start;
  }
  void dfs(const string& node) {
    for (int x = 0; x < K; x++) {
      string nxt = node + char('0' + x);
      if (!visited.count(nxt)) {
        visited.insert(nxt);
        dfs(nxt.substr(1));
        res.push_back('0' + x);
      }
    }
  }
};
Time: O(k^n * n) Space: O(k^n * n)