Recover Original List From Subsequences - Google Top Interview Questions


Problem Statement :


Given a two-dimensional list of integers lists, where each list is a subsequence of an original list, return the original list. 

The original list contains unique numbers. There is guaranteed to be one unique solution.

Constraints

n * m ≤ 100,000 where n and m are the number of rows and columns in lists

Example 1

Input

lists = [

    [1, 3],

    [2, 3],

    [1, 2]

]

Output

[1, 2, 3]

Example 2

Input

lists = [

    [1, 2, 4],

    [2, 3, 4]

]

Output

[1, 2, 3, 4]

Example 3

Input

lists = [

    [1, 2, 3]

]

Output

[1, 2, 3]



Solution :



title-img




                        Solution in C++ :

vector<int> solve(vector<vector<int>>& lists) {
    unordered_map<int, vector<int>> edges;
    unordered_set<int> vertices;
    unordered_map<int, int> numParents;
    for (auto& list : lists) {
        vertices.insert(list[0]);
        for (int i = 1; i < list.size(); i++) {
            vertices.insert(list[i]);
            edges[list[i - 1]].push_back(list[i]);
            numParents[list[i]]++;
        }
    }
    vector<int> ret;
    for (int vertex : vertices) {
        if (numParents[vertex] == 0) {
            ret.push_back(vertex);
        }
    }
    for (int i = 0; i < ret.size(); i++) {
        for (int child : edges[ret[i]]) {
            if (--numParents[child] == 0) {
                ret.push_back(child);
            }
        }
    }
    return ret;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[] solve(int[][] lists) {
        // normalize the numbers
        TreeSet<Integer> nums = new TreeSet<Integer>();
        for (int[] list : lists) {
            for (int l : list) nums.add(l);
        }
        int N = 0;
        TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>();
        ArrayList<Integer> sorted = new ArrayList<Integer>();
        for (int n : nums) {
            tm.put(n, N);
            sorted.add(n);
            N++;
        }

        ArrayList<Integer>[] graph = new ArrayList[N];
        int[] prev = new int[N];
        for (int i = 0; i < N; i++) graph[i] = new ArrayList<Integer>();
        for (int[] list : lists) {
            for (int i = 1; i < list.length; i++) {
                graph[tm.get(list[i - 1])].add(tm.get(list[i]));
                prev[tm.get(list[i])] += 1;
            }
        }

        int cur = -1;
        for (int i = 0; i < N; i++) {
            if (prev[i] == 0) {
                cur = i;
                break;
            }
        }

        int[] ans = new int[N];
        int index = 0;
        while (cur >= 0) {
            ans[index] = sorted.get(cur);
            index++;
            for (int n : graph[cur]) {
                prev[n] -= 1;
            }
            int next = -1;
            for (int n : graph[cur]) {
                if (prev[n] == 0) {
                    next = n;
                    break;
                }
            }
            cur = next;
        }
        return ans;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, A):
        graph = defaultdict(list)
        for row in A:
            for i in range(len(row) - 1):
                graph[row[i]].append(row[i + 1])
                graph[row[i + 1]]

        seen = set()

        def dfs(node):
            if node in seen:
                return
            seen.add(node)
            for nei in graph[node]:
                if nei not in seen:
                    dfs(nei)
            post.append(node)

        post = []
        for u in graph:
            dfs(u)
        return post[::-1]
                    


View More Similar Problems

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →