
Consider the subsequences = [[1,3,9], [3,9,5]], for the given subsequences the output array could be [1, 3, 9, 5] as:
1 is before 3 and 9
5 is after 3 and 9
3 is before 9
The first line of input contains an integer ‘T’ denoting the number of test cases. The description of ‘T’ test cases follows.
The first line of each test case contains an integer ‘N’ denoting the number of subsequences.
The next ‘N’ lines contain space-separated integers of the given subsequence.
For each test case, print "CORRECT" if the array formed with the subsequences is correct. Otherwise, print "INCORRECT".
For each test case, print a separate line.
1 <= T <= 10
1 <= N <= 10^3
1 <= M <= 10^3
0 <= arr[i] <= 10^6
Time limit: 1 sec
In this approach, we know that a number appearing before any other number in a subsequence will occur before the final array. Therefore the ordering of the numbers will remain the same.
We will create a directed graph from the given subsequences, which will be acyclic. Then will perform a topological search on the graph.
We will create a topologicalSort(node, graph, visited, nodes) which will perform a topological sort on the graph. Here node is the current node, visited is a set of previously visited nodes, and nodes are the list of nodes in topological order.
Algorithm:
In this approach, like the previous approach, we will find the topological sort of directed graph. Here we will use Kahn’s Algorithm.
According to Kahn algorithm:
We create topologicalSort(graph), which will return the topological sort of the graph
Algorithm: