Skip to content

Commit f9f2ac3

Browse files
committed
Two-Hundred-Twenty-Five Commit: Add Reconstructing a Sequence problem to Topological Sort Section
1 parent 28a1ed9 commit f9f2ac3

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package Topological_Sort;
2+
3+
// Problem Statement: Reconstructing a Sequence (hard)
4+
// LeetCode Question: 444. Sequence Reconstruction
5+
6+
import java.util.*;
7+
8+
public class Problem_6_Reconstructing_A_Sequence {
9+
10+
public boolean canConstruct(int[] originalSeq, int[][] sequences) {
11+
List<Integer> sortedOrder = new ArrayList<>();
12+
if (originalSeq.length <= 0)
13+
return false;
14+
15+
// a. Initialize the graph
16+
HashMap<Integer, Integer> inDegree = new HashMap<>(); // count of incoming edges for every vertex
17+
HashMap<Integer, List<Integer>> graph = new HashMap<>(); // adjacency list graph
18+
for (int[] seq : sequences) {
19+
for (int i = 0; i < seq.length; i++) {
20+
inDegree.putIfAbsent(seq[i], 0);
21+
graph.putIfAbsent(seq[i], new ArrayList<Integer>());
22+
}
23+
}
24+
25+
// b. Build the graph
26+
for (int[] seq : sequences) {
27+
for (int i = 1; i < seq.length; i++) {
28+
int parent = seq[i - 1], child = seq[i];
29+
graph.get(parent).add(child);
30+
inDegree.put(child, inDegree.get(child) + 1);
31+
}
32+
}
33+
34+
// if we don't have ordering rules for all the numbers we'll not able to uniquely
35+
// construct the sequence
36+
if (inDegree.size() != originalSeq.length)
37+
return false;
38+
39+
// c. Find all sources i.e., all vertices with 0 in-degrees
40+
Queue<Integer> sources = new LinkedList<>();
41+
for (Map.Entry<Integer, Integer> entry : inDegree.entrySet()) {
42+
if (entry.getValue() == 0)
43+
sources.add(entry.getKey());
44+
}
45+
46+
// d. For each source, add it to the sortedOrder and subtract one from all of its
47+
// children's in-degrees if a child's in-degree becomes zero, add it to sources queue
48+
while (!sources.isEmpty()) {
49+
if (sources.size() > 1)
50+
return false; // more than one sources mean, there is more than one way to
51+
// reconstruct the sequence
52+
if (originalSeq[sortedOrder.size()] != sources.peek())
53+
return false; // the next source (or number) is different from original sequence
54+
int vertex = sources.poll();
55+
sortedOrder.add(vertex);
56+
// get the node's children to decrement their in-degrees
57+
List<Integer> children = graph.get(vertex);
58+
for (int child : children) {
59+
inDegree.put(child, inDegree.get(child) - 1);
60+
if (inDegree.get(child) == 0)
61+
sources.add(child);
62+
}
63+
}
64+
65+
// if sortedOrder's size is not equal to original sequence's size, there is no
66+
// unique way to construct
67+
return sortedOrder.size() == originalSeq.length;
68+
}
69+
70+
}

0 commit comments

Comments
 (0)