## Google Interview Question

SDE-2s**Country:**United States

**Interview Type:**In-Person

Solved by finding a Hamiltonian path of size K^N

```
unordered_set<string> visited;
bool crackSafeHelp(const string &start,string &res,int k,int pow){
if(visited.size() == pow){
return true;
}
string newNode = start.substr(1);
for(int i = 0; i < k; ++i){
string digit = to_string(i);
string temp = newNode + digit;
if(visited.find(temp) == visited.end()){
res += digit;
visited.insert(temp);
if(crackSafeHelp(temp,res,k,pow)){
return true;
}
visited.erase(temp);
res.pop_back();
}
}
return false;
}
string crackSafe(int n, int k) {
int power = pow(k,n);
string start(n,'0');
string res(n,'0');
visited.insert(start);
crackSafeHelp(start,res,k,power);
return res;
}
```

slightly modified leetcode solution so that it works on both num and alphabet.

```
class Solution(object):
# n: length
# k: alphabet
def DeBruijn(self, n, k):
seen = set()
answer = []
try:
alphabet = list(map(str, range(k)))
except(ValueError, TypeError):
alphabet = k
def dfs(node):
for x in alphabet:
neighbor = node + x
if neighbor not in seen:
seen.add(neighbor)
dfs(neighbor[1:])
answer.append(x)
dfs(alphabet[0] * (n-1))
# print(seen)
return "".join(answer) + alphabet[0] * (n-1)
```

This is a De Bruijn sequence problem.

- adr October 09, 2018See https://en.wikipedia.org/wiki/De_Bruijn_sequence#Algorithm