[LeetCode] Sequence Reconstruction

444. Sequence Reconstruction

Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

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
58
59
class Solution {
private:
void makeGraph(unordered_map<int, list<int>> &behinds, unordered_map<int, int> &countsOfFront, set<int> &nodes, vector<vector<int>> &seqs) {
for(vector<int> vec : seqs) {
for(int i = 0; i < vec.size(); i++) {
nodes.insert(vec[i]);

if(i) {
countsOfFront[vec[i]] += 1;
behinds[vec[i - 1]].push_back(vec[i]);
}
}
}
}

queue<int> getFrontNodes(set<int> &nodes, unordered_map<int,int> countsOfFront) {
queue<int> res;

for(int node : nodes) {
if(!countsOfFront[node]) {
res.push(node);
countsOfFront.erase(node);
}
}

return res;
}
public:
bool sequenceReconstruction(vector<int>& org, vector<vector<int>>& seqs) {
unordered_map<int, list<int>> behinds;
unordered_map<int, int> countsOfFront;
set<int> nodes;

makeGraph(behinds, countsOfFront, nodes, seqs);

queue<int> q = getFrontNodes(nodes, countsOfFront);
vector<int> res;

while(!q.empty()) {
if(q.size() > 1)
return false;

res.push_back(q.front());

for(int num : behinds[q.front()]) {
countsOfFront[num]--;

if(!countsOfFront[num]) {
q.push(num);
countsOfFront.erase(num);
}
}

q.pop();
}

return countsOfFront.empty() && res == org;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/17/PS/LeetCode/sequence-reconstruction/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.