Build original array from the given sub | Function to add edge to graph ; Function to calculate indegrees of all the vertices ; If there is an edge from i to x then increment indegree of x ; Function to perform topological sort ; Push every node to the queue which has no incoming edge ; Since edge u is removed , update the indegrees of all the nodes which had an incoming edge from u ; Function to generate the array from the given sub - sequences ; Create the graph from the input sub - sequences ; Add edge between every two consecutive elements of the given sub - sequences ; Get the indegrees for all the vertices ; Get the topological order of the created graph ; Size of the required array ; Given sub - sequences of the array ; Get the resultant array as vector ; Printing the array
function addEdge ( adj , u , v ) { adj [ u ] . push ( v ) ; } function getindeg ( adj , V , indeg ) { for ( let i = 0 ; i < V ; i ++ ) { for ( let x = 0 ; x < adj [ i ] . length ; x ++ ) { indeg [ adj [ i ] [ x ] ] = indeg [ adj [ i ] [ x ] ] + 1 ; } } } function topo ( adj , V , indeg ) { let q = [ ] ; for ( let i = 0 ; i < V ; i ++ ) { if ( indeg [ i ] == 0 ) { q . push ( i ) ; } } let res = [ ] ; while ( q . length > 0 ) { let u = q . shift ( ) ; res . push ( u ) ; for ( let x = 0 ; x < adj [ u ] . length ; x ++ ) { indeg [ adj [ u ] [ x ] ] = indeg [ adj [ u ] [ x ] ] - 1 ; if ( indeg [ adj [ u ] [ x ] ] == 0 ) { q . push ( adj [ u ] [ x ] ) ; } } } return res ; } function makearray ( v , V ) { let adj = [ ] ; for ( let i = 0 ; i < V ; i ++ ) { adj . push ( [ ] ) ; } for ( let i = 0 ; i < v . length ; i ++ ) { for ( let j = 0 ; j < v [ i ] . length - 1 ; j ++ ) { addEdge ( adj , v [ i ] [ j ] , v [ i ] [ j + 1 ] ) ; } } let indeg = [ ] ; for ( let i = 0 ; i < V ; i ++ ) { indeg . push ( 0 ) ; } getindeg ( adj , V , indeg ) ; let res = topo ( adj , V , indeg ) ; return res ; } let n = 10 ; let subseqs = [ [ 9 , 1 , 2 , 8 , 3 ] , [ 6 , 1 , 2 ] , [ 9 , 6 , 3 , 4 ] , [ 5 , 2 , 7 ] , [ 0 , 9 , 5 , 4 ] ] ; let res = makearray ( subseqs , n ) ; for ( let x = 0 ; x < res . length ; x ++ ) { document . write ( res [ x ] + " " ) ; }