-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0444-sequence-reconstruction.js
More file actions
66 lines (55 loc) · 2.09 KB
/
0444-sequence-reconstruction.js
File metadata and controls
66 lines (55 loc) · 2.09 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Sequence Reconstruction
* Time Complexity: O(N + L)
* Space Complexity: O(N + L)
*/
var sequenceReconstruction = function (nums, sequences) {
const totalElements = nums.length;
const adjacencyList = new Map();
const nodeInDegrees = new Array(totalElements + 1).fill(0);
for (let nodeIdentifier = 1; nodeIdentifier <= totalElements; nodeIdentifier++) {
adjacencyList.set(nodeIdentifier, []);
}
for (const currentSequence of sequences) {
for (let elementPosition = 1; elementPosition < currentSequence.length; elementPosition++) {
const predecessorNode = currentSequence[elementPosition - 1];
const successorNode = currentSequence[elementPosition];
adjacencyList.get(predecessorNode).push(successorNode);
nodeInDegrees[successorNode]++;
}
}
const topologicalQueue = [];
for (let currentNumber = 1; currentNumber <= totalElements; currentNumber++) {
if (nodeInDegrees[currentNumber] === 0) {
topologicalQueue.push(currentNumber);
}
}
if (topologicalQueue.length !== 1) {
return false;
}
const finalSequence = [];
while (topologicalQueue.length > 0) {
if (topologicalQueue.length > 1) {
return false;
}
const poppedNode = topologicalQueue.shift();
finalSequence.push(poppedNode);
const connectedNeighbors = adjacencyList.get(poppedNode);
for (let neighborIterator = 0; neighborIterator < connectedNeighbors.length; neighborIterator++) {
const specificNeighbor = connectedNeighbors[neighborIterator];
nodeInDegrees[specificNeighbor]--;
if (nodeInDegrees[specificNeighbor] === 0) {
topologicalQueue.push(specificNeighbor);
}
}
}
if (finalSequence.length !== totalElements) {
return false;
}
for (let sequenceChecker = 0; sequenceChecker < totalElements; sequenceChecker++) {
if (finalSequence[sequenceChecker] !== nums[sequenceChecker]) {
return false;
}
}
return true;
};