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

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →

Library Query

A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra

View Solution →