-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0753-cracking-the-safe.js
More file actions
48 lines (39 loc) · 1.23 KB
/
0753-cracking-the-safe.js
File metadata and controls
48 lines (39 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Cracking The Safe
* Time Complexity: O(k^n * n)
* Space Complexity: O(k^n * n)
*/
var crackSafe = function (n, k) {
if (n === 1) {
let singleDigitResult = "";
for (let currentNumber = 0; currentNumber < k; currentNumber++) {
singleDigitResult += currentNumber.toString();
}
return singleDigitResult;
}
const visitedSubstrings = new Set();
const totalExpectedCount = k ** n;
let finalPassword = "0".repeat(n);
visitedSubstrings.add(finalPassword);
function exploreCombinations(currentPasswordState) {
if (visitedSubstrings.size === totalExpectedCount) {
return true;
}
const nextPrefix = currentPasswordState.slice(-n + 1);
for (let nextPin = 0; nextPin < k; nextPin++) {
const candidatePassword = nextPrefix + nextPin.toString();
if (!visitedSubstrings.has(candidatePassword)) {
visitedSubstrings.add(candidatePassword);
finalPassword += nextPin.toString();
if (exploreCombinations(candidatePassword)) {
return true;
}
finalPassword = finalPassword.slice(0, -1);
visitedSubstrings.delete(candidatePassword);
}
}
return false;
}
exploreCombinations(finalPassword);
return finalPassword;
};