Build original array from the given sub-sequences

Given an integer N and valid subsequences of an array of integers where every element is distinct and from the range [0, N – 1], the task is to find the original array.

Examples:

Input: N = 6, v[] = {
{1, 2, 3},
{1, 2},
{3, 4},
{5, 2},
{0, 5, 4}}
Output: 0 1 5 2 3 4

Input: N = 10, v[] = {
{9, 1, 2, 8, 3},
{6, 1, 2},
{9, 6, 3, 4},
{5, 2, 7},
{0, 9, 5, 4}}
Output: 0 9 6 5 1 2 8 7 3 4

Approach: Build a graph from given subsequences. Select each sub-sequence one by one and add an edge between two adjacent elements in the sub-sequence. After building the graph, perform topological sorting on the graph.
Refer topological sorting for understanding topological sort. This topological ordering is the required array.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to add edge to graph
void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
}
  
// Function to calculate indegrees of all the vertices
void getindeg(vector<int> adj[], int V, vector<int>& indeg)
{
    // If there is an edge from i to x
    // then increment indegree of x
    for (int i = 0; i < V; i++) {
        for (auto x : adj[i]) {
            indeg[x]++;
        }
    }
}
  
// Function to perform topological sort
vector<int> topo(vector<int> adj[], int V, vector<int>& indeg)
{
    queue<int> q;
  
    // Push every node to the queue
    // which has no incoming edge
    for (int i = 0; i < V; i++) {
        if (indeg[i] == 0)
            q.push(i);
    }
    vector<int> res;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        res.push_back(u);
  
        // Since edge u is removed, update the indegrees
        // of all the nodes which had an incoming edge from u
        for (auto x : adj[u]) {
            indeg[x]--;
            if (indeg[x] == 0)
                q.push(x);
        }
    }
    return res;
}
  
// Function to generate the array
// from the given sub-sequences
vector<int> makearray(vector<vector<int> > v, int V)
{
  
    // Create the graph from the input sub-sequences
    vector<int> adj[V];
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size() - 1; j++) {
  
            // Add edge between every two consecutive
            // elements of the given sub-sequences
            addEdge(adj, v[i][j], v[i][j + 1]);
        }
    }
  
    // Get the indegrees for all the vertices
    vector<int> indeg(V, 0);
    getindeg(adj, V, indeg);
  
    // Get the topological order of the created graph
    vector<int> res = topo(adj, V, indeg);
    return res;
}
  
// Driver code
int main()
{
    // Size of the required array
    int n = 10;
  
    // Given sub-sequences of the array
    vector<vector<int> > subseqs{ { 9, 1, 2, 8, 3 },
                                  { 6, 1, 2 },
                                  { 9, 6, 3, 4 },
                                  { 5, 2, 7 },
                                  { 0, 9, 5, 4 } };
  
    // Get the resultant array as vector
    vector<int> res = makearray(subseqs, n);
  
    // Printing the array
    for (auto x : res) {
        cout << x << " ";
    }
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
from collections import deque
adj=[[] for i in range(100)]
  
# Function to add edge to graph
def addEdge(u, v):
    adj[u].append(v)
  
# Function to calculate indegrees of all the vertices
def getindeg(V,indeg):
  
    # If there is an edge from i to x
    # then increment indegree of x
    for i in range(V):
        for x in adj[i]:
            indeg[x] += 1
  
  
# Function to perform topological sort
def topo(V,indeg):
    q = deque()
  
    # Push every node to the queue
    # which has no incoming edge
    for i in range(V):
        if (indeg[i] == 0):
            q.appendleft(i)
    res=[]
    while (len(q) > 0):
        u = q.popleft()
        res.append(u)
  
        # Since edge u is removed, update the indegrees
        # of all the nodes which had an incoming edge from u
        for x in adj[u]:
            indeg[x]-=1
            if (indeg[x] == 0):
                q.appendleft(x)
  
    return res
  
  
# Function to generate the array
# from the given sub-sequences
def makearray(v, V):
  
    # Create the graph from the input sub-sequences
    for i in range(len(v)):
        for j in range(len(v[i])-1):
  
            # Add edge between every two consecutive
            # elements of the given sub-sequences
            addEdge(v[i][j], v[i][j + 1])
  
  
    # Get the indegrees for all the vertices
    indeg=[0 for i in range(V)]
    getindeg(V, indeg)
  
    # Get the topological order of the created graph
    res = topo(V, indeg)
    return res
  
# Driver code
  
# Size of the required array
n = 10
  
# Given sub-sequences of the array
subseqs=[ [ 9, 1, 2, 8, 3 ],
        [ 6, 1, 2 ],
        [ 9, 6, 3, 4 ],
        [ 5, 2, 7 ],
        [ 0, 9, 5, 4 ] ]
  
# Get the resultant array as vector
res = makearray(subseqs, n)
  
# Printing the array
for x in res:
    print(x,end=" ")
      
# This code is contributed by mohit kumar 29

chevron_right


Output:

0 9 6 5 1 2 8 7 3 4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.