-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret-string.js
57 lines (55 loc) · 1.82 KB
/
secret-string.js
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
49
50
51
52
53
54
55
56
57
var recoverSecret = function (triplets) {
var letterMap = new Map();
var returnStr = "";
for (let i = 0; i < triplets.length; ++i) {
let individualTriplet = triplets[i];
for (let x = 0; x < individualTriplet.length; ++x) {
let indiLetter = individualTriplet[x];
if (!letterMap.get(indiLetter)) {
letterMap.set(indiLetter, new Set());
}
if (x < individualTriplet.length - 1) {
let nextLetter = individualTriplet[x + 1];
let successors = letterMap.get(indiLetter);
successors.add(nextLetter);
letterMap.set(indiLetter, successors);
}
}
}
var Q = [];
var predecessorMap = new Map();
for (const [key, value] of letterMap.entries()) {
if (!predecessorMap.get(key)) {
predecessorMap.set(key, new Set());
}
}
for (const [key, value] of letterMap.entries()) {
value.forEach((successor) => {
let predecessors = predecessorMap.get(successor);
predecessors.add(key);
predecessorMap.set(successor, predecessors);
});
}
for (const [key, value] of predecessorMap.entries()) {
if (value.size === 0) {
Q.push(key);
}
}
while (Q.length !== 0) {
let letter = Q.pop();
returnStr += letter;
let successors = letterMap.get(letter);
successors.forEach((key) => {
let predecessors = predecessorMap.get(key);
predecessors.forEach((pred) => {
if (pred === letter)
predecessors.delete(pred);
});
if (predecessors.size === 0) {
Q.push(key);
}
});
}
return returnStr;
}
module.exports = recoverSecret;